21 votes
Accepted

Getting field names of layer using PyQGIS

To get field names with fields() method or other field properties (length, type, comment, ...) you can use: field_names = [field.name() for field in layer.fields()] # ['id', 'attr1', 'attr2', 'attr3'] ...
16 votes
Accepted

Running PyQGIS algorithm on selected features in layer

You need add the layer to project. For add without showing it use: QgsProject.instance().addMapLayer(layer1, False) Example using only one layer: layer1 = QgsVectorLayer(r"C:\test\grassland....
  • 7,580
15 votes
Accepted

QGIS 3.0.2 Check if a field exists in a layer in Python

Welcome to GIS.SE! As you thought, there is a way to know if a field exists in a layer not by iterating features but by looking at the layer structure. In the QGIS Layers Panel, select a layer. Then ...
15 votes

Getting field names of layer using PyQGIS

List field names with dataProvider() method from qgis.utils import iface # get active layer if not already set layer = iface.activeLayer() prov = layer.dataProvider() field_names = [field.name() ...
  • 933
14 votes

Modify Attribute Table while opening using PyQGIS

Interesting question! I couldn't find any native signal emitted when an attribute table is opened or closed so I would call this solution a fairly inelegant workaround but it seems to work well enough....
  • 18k
13 votes
Accepted

Modifying layer name in the layout legend with PyQGIS 3

You must set setUseLayerName() to False to name legend tree layers manually. # # previous lines # for i, layer in enumerate(layersToAdd): tree_layer = root.addLayer(layer) tree_layer....
12 votes
Accepted

Getting layer by name using PyQGIS 3

If you are sure there is one layer named LAYER_NAME, the shortest way: layer = QgsProject.instance().mapLayersByName('LAYER_NAME')[0] In that way, you can get a layer in a group layer. print(layer) ...
12 votes
Accepted

Getting ordered list of IDs of selected features using PyQGIS

Use this script: selection = [] def selection_changed(selected, deselected, clearAndSelect): global selection # If the user deselects feature(s), remove ID's from list if deselected: ...
12 votes
Accepted

Field calculator: generate n fields reporting n-largest values

You can use this script. First, select a the layer, then run the script. It adds the result as a memory layer. You should save the result as a new file manually or using a code. input_layer = iface....
12 votes
Accepted

Filtering with setSubsetString using PyQGIS

Change layer.setSubsetString("GAMME_DE_S=VSR") to layer.setSubsetString("GAMME_DE_S='VSR'") Then to add the layer, if not layer.isValid(): print("Layer failed to load!&...
  • 29.5k
11 votes
Accepted

Find QGIS 3 plugin folder location with PyQGIS

try: from qgis.core import QgsApplication QgsApplication.qgisSettingsDirPath() for show profiles folder https://qgis.org/api/classQgsApplication.html#a89ad50b0d0fd60ccae803f22f6c5cf46
  • 7,580
11 votes

Creating vector layer in memory following the QGIS Python Programming Cookbook

If you are using QGIS 3 that book is outdated in hopes of improving your abilities around PyQGIS 3. Following code has 3 necessary corrections to run as expected: layer = QgsVectorLayer('Point?crs=...
  • 27.7k
11 votes
Accepted

Print Layout Items. setExtent() and attemptResize()

The order of when you set the extent, add the map to the layout, and resize the rectangle is important. Steps to add a map to a new layout in QGIS 3. Instantiate the map object with QgsLayoutItemMap(...
  • 535
11 votes
Accepted

Adding tile layer via PyQGIS

Here is the code which is working for me: urlWithParams = 'type=xyz&url=https://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857' rlayer = ...
  • 892
11 votes
Accepted

Creating grid with PyQGIS

You use wrong TYPE code. You have to use 2 for rectangular grid. 3 means diamond. params = {'TYPE':2, ...} # 2: rectangle For more details about the algorithm try import processing processing....
11 votes

Checking if active layer is GeoPackage using PyQGIS

You can use: if iface.activeLayer().storageType() != 'GPKG': print('Active layer is not a GeoPackage format')
  • 1,260
10 votes
Accepted

Joining layers with PyQGIS 3

The class has been renamed from QgsVectorJoinInfo to QgsVectorLayerJoinInfo. You now need to call each join function with their associated parameter: ... csvField = 'id' shpField = 'ID' joinObject = ...
  • 73.8k
10 votes
Accepted

Exporting layout in standalone script with QGIS 3

Here is the solution working for me. The python file must be in the same directory as the QGIS 3 project file : #!/usr/bin/env python3 import os from qgis.core import (QgsProject, QgsLayoutExporter, ...
  • 14.5k
10 votes
Accepted

PyQGIS - Managing print layouts

You attempt to set a name to a deleted object. You need to create a new object : [...] for layout in layouts_list: if layout.name() == layoutName: manager.removeLayout(layout) layout = ...
  • 14.5k
10 votes
Accepted

Apply a color ramp to vector layer using PyQGIS3

Updated answer: Below is a recipe to apply a graduated renderer based on values in an attribute field, specifying the number of classes and color ramp. # Set layer name and desired paremeters ...
  • 18k
10 votes
Accepted

Zoom to feature by clicking cell in the Attribute Table

I've found a temporary solution: layer = QgsProject.instance().mapLayersByName("LAYER_NAME")[0] attr_table = iface.showAttributeTable(layer) table = attr_table.findChildren(QTableView)[0] def ...
10 votes
Accepted

Get only fields with datatype int in PyQGIS

By type name (typeName()): int_types = ["Integer", "Integer64"] int_fields = [field for field in iface.activeLayer().fields() if field.typeName() in int_types] OR by type number (...
10 votes
Accepted

Adding page number to an atlas layout with PyQGIS 3

You can use the following structure: # # previous lines # page_label = QgsLayoutItemLabel(layout) # # other label settings here # text = "[% 'Page: ' + to_string(@atlas_featurenumber ) + '/' +...
10 votes
Accepted

Populating attributes while creating polygons in for-loop from CSV using PyQGIS

You set feature fields to empty QgsFields. fields = QgsFields() # fields is empty feature.setFields(fields) # you set the empty fields Instead, pass layer.fields() to QgsFeature. feature = QgsFeature(...
10 votes
Accepted

Iterating over features of a same layer

If you use != (in n.id()!=init.id()) inside the "if" statement, you compare the items (ex: comparing 2 to 1) you've compared before (ex: comparing 1 to 2). In this case, both items are ...
10 votes
Accepted

PyQGIS to set masked symbol layer and mask source

Label masking information is not stored in the qml-file? I guess "Masked symbol layers" and "Mask sources" settings are not stored in both qml file and Geopackage. I just realized ...
9 votes

How can I get the path for an input layer in a QGIS 3 script?

The input parameters can be accessed as a dictionary object, so parameters['SPECIES_POINTS'] will give you the path to the input layer. The call to the algorithm would then be: pointsReprojected = ...
9 votes
Accepted

Moving a geometry using PyQGIS3

To change QgsFeature geometry in QGIS 3 you have to call setGeometry() explicitly. geom = feat.geometry() geom.translate(100, 100) feat.setGeometry(geom) Explanation: In QGIS 2 geometry() returns a ...
  • 660
9 votes
Accepted

Applying categorized render to polygons

Improved answer The trick is to use renderer.updateColorRamp(ramp) instead of renderer.setSourceColorRamp(ramp). Here is a working code snippet to create categories from unique values, pass them to a ...
  • 18k
9 votes
Accepted

Add Help Menu entry in QGIS 3 from `startup.py`

Great idea you need place startup.py in C:\Users\<username>\AppData\Roaming\QGIS\QGIS3 and add missing import ,and voilá from qgis.utils import iface from PyQt5.QtWidgets import QAction import ...
  • 7,580

Only top scored, non community-wiki answers of a minimum length are eligible