Hot answers tagged

19 votes
Accepted

Explaining long computing time of Python code

Here are some issues with your script: I've already learned that using GeoJSON for analyzing is a too bad idea. The script below that takes 20 seconds when I use GeoPackage takes about 8-10 hours ...
Kadir Şahbaz's user avatar
12 votes
Accepted

Calling "Remove empty layers" plugin from the Python Console in QGIS

Yes. It is possible using the following lines. from RemoveEmptyLayers.removeemptylayers import RemoveEmptyLayers remove = RemoveEmptyLayers(iface) remove.run() Please also check this answer to ...
Kadir Şahbaz's user avatar
12 votes
Accepted

Append several layers to a GeoJSON file with PyQGIS

You need to tell the code what to do when it encounters the same file. For this, you need to use for the second export: options = QgsVectorFileWriter.SaveVectorOptions() options.actionOnExistingFile = ...
Kadir Şahbaz's user avatar
12 votes
Accepted

Creating one meter line from a point in the direction of a other line using PyQGIS

Change the for loop as follows: for point_feat in point_layer.getFeatures(): point_geom = point_feat.geometry() nearest_ids = line_index.nearestNeighbor(point_geom.asPoint(), 1) ...
Kadir Şahbaz's user avatar
12 votes
Accepted

"'QgsPyExpressionFunction' object is not callable" when using custom function within QgsPyExpressionFunctions in PyQGIS

The problem is not about feature or parent parameter. It arises because the string in QgsExpression is not a valid QGIS expression. attrmap_filtered.values() in the expression is a Pythonic syntax, ...
Kadir Şahbaz's user avatar
12 votes

Rotating features with multiple geometries in one layer using PyQGIS

There are several things that I would improve: do not forget to start/startEditing, end/endEditCommand(), and commit/commitChanges() editings use the setGeometry() method properly, otherwise the ...
Taras's user avatar
  • 31.3k
11 votes
Accepted

Deleting parts of MultiPolygon based on area using PyQGIS

You can make a new part list from the MultiPolygon instead of deleting the parts. layer = iface.activeLayer() # Minimum area threshold minimum_area = 2000 layer.startEditing() # Loop through all ...
Kadir Şahbaz's user avatar
11 votes

Install Python library in QGIS as non-administrator

Since you don't have admin privileges, when you install a package using QGIS Python Console/Editor as follows, it is installed to C:\Users\user\AppData\Roaming folder. import subprocess subprocess....
Kadir Şahbaz's user avatar
11 votes
Accepted

Closing QGIS project without saving using PyQGIS

As @etrimaille stated, "editing a layer" and "saving the project" are two different things, and you can edit data (and saving) without saving the project itself. A project is not a ...
Kadir Şahbaz's user avatar
11 votes
Accepted

Translating raster from floating point to int16 increases size

Your 5 Mb inputs are compressed and your outputs are not. Your 40 Mb inputs may be compressed, but didn't compress well (very noisy data leads to poor compression, a random raster can actually ...
user2856's user avatar
  • 64.8k
10 votes

Creating spatial index in standalone script as part of output vector layer using PyQGIS

If you use layer_out.dataProvider().createSpatialIndex() you don't get that error. To get the error you must use layer_out.createSpatialIndex(). The code in the question doesn't throw the error: ...
Kadir Şahbaz's user avatar
10 votes

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 ...
Kadir Şahbaz's user avatar
10 votes
Accepted

Performing basic labelling with PyQGIS

There is no problem with @Kezah's answer. I've edited the script and it works. Please check it. Avoid using startEditing() and dataProvider().addFeatures() together. Use either one. If you construct a ...
Kadir Şahbaz's user avatar
10 votes
Accepted

Why angleAtVertex() returns different value than angle_at_vertex in Field Calculator using PyQGIS

angle_at_vertex() returns the angle in degrees: anlge_at_vertex($geometry, 0) -> 38.618825502347555 degree angleAtVertex() returns the angle in radians: feature.geometry().angleAtVertex(0) -> 0....
Kadir Şahbaz's user avatar
10 votes
Accepted

Get name of labeling rule with Python in QGIS

You have to use description method of class QgsRuleBasedLabeling.Rule. layer = iface.activeLayer() labeling = layer.labeling() for rule in labeling.rootRule().children(): print(rule.description())...
Kadir Şahbaz's user avatar
10 votes
Accepted

Running Python code easily for end users in QGIS

You can use the minimal plugin skeleton in this repository. Copy the files (only metadata and __init__ are required) to a new folder in plugin folder. Change the files' content as follows: Folder ...
Kadir Şahbaz's user avatar
10 votes
Accepted

Set the Units of a QgsGeometryGeneratorSymbolLayer object in PyQGIS

You have to use QgsUnitTypes.RenderMillimeters. layer = iface.activeLayer() mm = QgsUnitTypes.RenderMillimeters layer.renderer().symbol().symbolLayer(1).setUnits(mm) symbolLayer(1) must be an ...
Kadir Şahbaz's user avatar
10 votes
Accepted

Use PyQGIS to load Value Map against attribute

To set a value map widget with values loaded manually, you can just do something like: #QgsVectorLayer object vl = iface.activeLayer() # Get field index fld_idx = vl.fields().lookupField('...
Ben W's user avatar
  • 20.6k
10 votes
Accepted

Hiding/showing layers in legend does not work in QGIS standalone

QgsLayerTreeMapCanvasBridge must be in global scope. But you define bridge in add_legend method's scope. Therefore, variable bridge is gone after add_legend finished. One of the solutions: Add bridge ...
Kadir Şahbaz's user avatar
9 votes
Accepted

QGIS Python loop integer with select by expression

You can use the following script structure: layer = iface.activeLayer() end_number = 5 # OS1, OS2, OS3, OS4, OS5 attribute_name = "attribute_name" # field name containing OS values for i ...
Kadir Şahbaz's user avatar
9 votes

Making dissolve output as temporary layer using PyQGIS

In more recent versions of QGIS, do not forget to include the 'SEPARATE_DISJOINT' argument, see the Changelog for QGIS 3.26 for more details. So, your code may look like this: from qgis import ...
Taras's user avatar
  • 31.3k
9 votes
Accepted

Accessing processing.run() output layer in PyQGIS

Regarding the question: "do I need to use is_child_algorithm=True?", you need to use it if the algorithm you are running is being run as a child or sub-algorithm, if you like, inside the ...
Ben W's user avatar
  • 20.6k
9 votes
Accepted

Zooming to each vector layer extent, one at a time, using PyQGIS

You can solve your issue using QTimer which controls when to execute functions and it's asynchronous, i.e., it allows other functions to continue to run (think of a map.refresh()) while waiting some ...
Kadir Şahbaz's user avatar
9 votes

"AttributeError: 'dict' object has no attribute 'fields'" error when creating and deleting fields in the attribute table using PyQGIS

I could get the same error: Traceback (most recent call last): File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "<...
Taras's user avatar
  • 31.3k
9 votes

PyQt signal when layer name is changed in PyQGIS

Use the nameChanged signal of QgsLayerTreeNode class. from qgis.core import QgsProject def name_changed(node, name): print(f"New Name: {name}") QgsProject.instance().layerTreeRoot()...
Kadir Şahbaz's user avatar
9 votes
Accepted

Use PyQGIS to save memory layer to GeoPackage that does not already exist

You can use the following lines in your PyQGIS script to make an empty GeoPackage. from osgeo import ogr gpkg_path = "c:/test/test.gpkg" ds = ogr.GetDriverByName('GPKG').CreateDataSource(...
Kadir Şahbaz's user avatar
8 votes
Accepted

What does context mean in PyQGIS?

I would like to explain as far as I know what context means. Context can be seen as a bucket to pass information around.(Ref) Let's say you write a function (funcA) which calls another function (...
menes's user avatar
  • 1,421
8 votes
Accepted

PyQGIS: setting layer styles with QML file from URL

Instead of loadNamedStyle use the method importNamedStyle. It can directly receive a XML document as argument instead of a file path. Creating an XML document is simply using QDomDocument::setContent()...
CodeBard's user avatar
  • 3,306
8 votes
Accepted

"Could not load source layer for MASK: invalid value" error when iterating over features in polygon layer and clipping raster by mask layer in PyQGIS

Apparently, the type of Mask layer should be a [vector: polygon] i.e. QgsVectorLayer, see documentation. Also, visible via processing.algorithmHelp("gdal:cliprasterbymasklayer"): ... MASK: ...
Taras's user avatar
  • 31.3k
8 votes
Accepted

TypeError when converting shapefiles to KMLs using PyQGIS

According to the documentation the first argument should be a QgsVectorLayer, which is why you are getting the unexpected type error. You are also missing the QgsCoordinateReferenceSystem parameter. ...
Matt's user avatar
  • 14.7k

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