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']
...
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 ...
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....
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() ...
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....
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!&...
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
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
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=...
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(...
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 = ...
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
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
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 = ...
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, ...
11
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 = ...
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, ...
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
...
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')
10
votes
Accepted
Changing QGIS system SVG path with PyQGIS
Tested in QGIS 3.2 Python Console under Ubuntu 18.04:
To find the settings you need, you can use
settings = QSettings().allKeys()
This will create a list of all available Settings (it can help to ...
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 ...
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 ...
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
Returning only listed column values in PyQGIS
You should "very often" use QgsFeatureRequest:
https://qgis.org/api/classQgsFeatureRequest.html
https://qgis.org/pyqgis/master/core/QgsFeatureRequest.html
If you need only a subset of ...
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.
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["...
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 ...
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 ) + '/' +...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
pyqgis-3 × 770qgis-3 × 335
pyqgis × 310
qgis × 255
python × 125
qgis-plugins × 92
qgis-processing × 72
print-composer × 33
layers × 25
pyqt5 × 22
fields-attributes × 20
python-3 × 19
attribute-table × 17
labeling × 15
postgis × 12
standalone × 12
raster × 11
layouts × 10
qgsvectorlayer × 10
gdal × 9
symbology × 9
geometry × 9
export × 9
style × 9
vector-layer × 9