15 votes

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'] ...
user avatar
13 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....
user avatar
  • 13.6k
13 votes
Accepted

Getting field names of layer using PyQGIS

List field names with dataProvider() method # get active layer if not already set layer = qgis.utils.iface.activeLayer() prov = layer.dataProvider() field_names = [field.name() for field in prov....
user avatar
  • 869
12 votes
Accepted

Change vector layer symbology PyQGIS 3?

The easiest for me would be to check the properties of the symbology layer which contains symbol properties affecting the whole layer: dir(symbol) >>>['DynamicRotation', 'Fill', 'Hybrid', '...
user avatar
  • 72.2k
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: ...
user avatar
11 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 ...
user avatar
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=...
user avatar
  • 25.9k
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(...
user avatar
  • 535
11 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....
user avatar
11 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....
user avatar
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')
user avatar
  • 1,198
10 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
user avatar
  • 7,186
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 = ...
user avatar
  • 72.2k
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 ...
user avatar
  • 13.6k
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 (...
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 ) + '/' +...
user avatar
10 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....
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(...
user avatar
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 = ...
user avatar
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 ...
user avatar
  • 13.6k
9 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 = ...
user avatar
  • 800
9 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!&...
user avatar
  • 28.6k
9 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 ...
user avatar
8 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 ...
user avatar
  • 620
8 votes
Accepted

Applying graduated renderer to polygon using PyQGIS 3?

I'm going to answer my own question in two ways. First, I'll use the example from the PyQGIS Developer Cookbook. I initially struggled with this example but eventually got it working, so here is a ...
user avatar
  • 1,621
8 votes
Accepted

Dissolving using PyQGIS?

The easiest approach is to run the algorithm through the GUI, and then look in the Processing "history". You'll see the equivalent Python command shown there for the operation you just performed via ...
user avatar
  • 26.2k
8 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 ...
user avatar
  • 7,186
8 votes

Field calculator: generate n fields reporting n-largest values

You can also use the following script without any Processing tool. The script doesn't create any layer, it adds fields to the active layer and assigns values. from PyQt5.QtCore import QVariant lyr = ...
user avatar
  • 3,479
8 votes
Accepted

How to set field attribute of selected features to NULL with PyQGIS 3

NULL is defined in qgis.core from qgis.core import NULL with edit(layer): for feature in layer.selectedFeatures(): feature.setAttribute('distance', NULL) layer.updateFeature(...
user avatar
8 votes

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

Personally, I prefer to use the changeAttributeValues() method of QgsVectorDataProvider (see API docs here) as I find it more reliable. This method takes an attributes map which is basically a ...
user avatar
  • 13.6k

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