Skip to main content
28 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'] ...
Kadir Şahbaz's user avatar
19 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 ...
Germán Carrillo's user avatar
16 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....
Ben W's user avatar
  • 21.7k
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() ...
grego's user avatar
  • 1,043
14 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....
Kadir Şahbaz's user avatar
14 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!&...
ThomasG77's user avatar
  • 30.9k
13 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
Fran Raga's user avatar
  • 7,848
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) ...
Kadir Şahbaz's user avatar
12 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=...
xunilk's user avatar
  • 30k
12 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(...
RobLabs's user avatar
  • 545
12 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 = ...
ncica's user avatar
  • 942
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: ...
Kadir Şahbaz's user avatar
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....
Kadir Şahbaz's user avatar
12 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....
Kadir Şahbaz's user avatar
11 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 = ...
Joseph's user avatar
  • 75.9k
11 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, ...
J. Monticolo's user avatar
  • 15.7k
11 votes
Accepted

Changing MultiLineString direction using PyQGIS

I will focus on the geometry creation part, because the feature editing part is fully explained in many places, including the example inside the question. I will use some Python list comprehension, ...
Javier JC's user avatar
  • 892
11 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 ...
Ben W's user avatar
  • 21.7k
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')
Leo Cardona's user avatar
  • 1,363
10 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 ...
barteksch's user avatar
  • 685
10 votes
Accepted

pyqgis - post-processing of layer output of QgsProcessingAlgorithm

Just to be more elaborate than the comment. Basically, the postProcessAlgorithm() does what it says. It also returns a value map, including the OUTPUT. However, you need to look up the layer in the ...
nilsnolde's user avatar
  • 487
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 = ...
J. Monticolo's user avatar
  • 15.7k
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 ...
Kadir Şahbaz's user avatar
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 (...
Kadir Şahbaz's user avatar
10 votes
Accepted

Changing layer properties for 3D View using PyQGIS

You should use setRenderer3D method of QgsMapLayer. layer.setRenderer3D(renderer) QgsVectorLayer inherits that method from QgsMapLayer.
Kadir Şahbaz's user avatar
10 votes
Accepted

Getting Polyline (Linestring) coordinates from line layer in QGIS

First, add a field (name: geometry, type: string, length: 1000 keep it long). Then use the following script: lyr = iface.activeLayer() with edit(lyr): for f in lyr.getFeatures(): f["...
Kadir Şahbaz's user avatar
10 votes

Alternative of iface for standalone PyQGIS application

iface is predefined variable in QGIS. It is defined while QGIS starts and refers to QGIS interface. That means you cannot use iface in your standalone application. You can use QgsProject.instance() to ...
Kadir Şahbaz's user avatar
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 ) + '/' +...
Kadir Şahbaz's user avatar
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(...
Kadir Şahbaz's user avatar
10 votes

Filtering with setSubsetString using PyQGIS

Pay attention to quotes: Subset string is an expression. You have to use single quotes for string values. A text placed between single quotes ('VSR') is interpreted as a string. Double quotes will ...
Kadir Şahbaz's user avatar

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