New answers tagged

0 votes

Changing layer name in QGIS by replacing only a part of it using Python

You just do 'string'.replace('st', 'ST') insdead of setting the actual layer name. Use layer.setName to set it propperly. https://qgis.org/pyqgis/master/core/QgsMapLayer.html#qgis.core.QgsMapLayer....
  • 5,750
0 votes

QGIS Bézier-editing plugin does not honor id-creating rule when saving new line feature

Basis: see the ** Partial Answer ** section in my edited question. After more studying of the C++ source I found this class: QgsVectorLayerUtils. It has a method createFeature which honors all ...
0 votes
Accepted

How to add/install library in python notebook or QGIS (python console)?

In your console example you have opened python and are trying to install the library. You'll need to install the library from outside of python. For QGIS it is easiest to do it from the OSGEO4W Shell ...
  • 3,050
1 vote

Single line with Dash stroke style with PyQGIS implementation

symbol = QgsLineSymbol.createSimple({'line_style':'dash','color':symbolColor, 'width':'1.5'}) layer.renderer().setSymbol(symbol) layer.triggerRepaint()
  • 23
0 votes

PyQGIS - Export multiple layouts as multiple PDF files

I read "manager.printLayouts" so I guess it's exporting cards from the print manager. if that's the case, this code exports each layout to a specific pdf manager = QgsProject.instance()....
  • 723
1 vote

How to start reading shapefile in QGIS using python console?

Take a look at Using Vector Layers. For example: shapefile_path = r'/home/bera/Desktop/GIStest/buildings.shp' layer = QgsVectorLayer(shapefile_path, 'templayer') #Create a layer object all_features = [...
  • 55.3k
2 votes

Importing multiple txt files using PyQGIS

You are missing skipLines=2. The most easy way to find out how the uri should look like is to load one example manually and than look into the Information section of the loaded layer. There you will ...
  • 1,290
0 votes

Remove reference to raster layer object PyQGIS

Try to move the QgsRasterLayer to the Core Thread. if r.isValid(): r.moveToThread(QCoreApplication.instance().thread()) rlayers.append(r) count = count + 1 I had issues with ...
  • 11
1 vote
Accepted

Copy QGIS Layer Style from one layer to another with PyQGIS

I guess there must be some easier method to do it. But so far I could only figure out doing so using QgsMapLayer.styleManager() as descibed at QgsMapLayerStyleManager() layerA = QgsProject.instance()....
  • 27.3k
1 vote

Getting geometry from attribute using PyQGIS

This format is known as EWKT (Extended Well-Known text, see https://postgis.net/docs/ST_GeomFromEWKT.html) and currently not supported in QGIS except for certain PostGIS contexts. You can see their ...
  • 8,847
0 votes

Getting the readable messagelevel of a Qgis.MessageLevel

With pure Python, you can do introspection and create your own useful translator : message_levels = { getattr(Qgis, i): i for i in dir(Qgis) if isinstance(getattr(Qgis, i), Qgis.MessageLevel) }...
  • 13.2k
2 votes

Getting the readable messagelevel of a Qgis.MessageLevel

As far as I am aware PyQt does not support iteration over names/values of Qt's enum types as you could do with standard python enums. Instead, you can get information on the enumerator via the ...
  • 1,941
2 votes
Accepted

How to trigger a "python action" by clicking on the concerned layer?

You can use the script below for your action: from qgis.PyQt import QtWidgets layer_id = '[%@layer_id%]' layer1 = QgsProject.instance().mapLayer(layer_id) layer2 = QgsProject.instance()....
  • 15.8k
0 votes

Getting the readable messagelevel of a Qgis.MessageLevel

They are a few functions having displayString in their name to convert an enum item to a "display string". Like https://api.qgis.org/api/classQgsWkbTypes.html#...
  • 6,110
1 vote
Accepted

Using SAGA Proessing in PyQgis Standanlone Script with batch file calling. "NameError: name 'processing' is not defined"

You need a few modifications to your Intersection.py file to import and initialize processing and also to initialize the qgis application for running a standalone script. This is based on answers to ...
  • 15.8k
2 votes

Setting project title with PyQGIS

The setTitle() method belongs to the QgsProject class, but you are trying to call it on the string object which is returned when you retrieve the current title. As per the docs, this method provides: ...
  • 15.8k
1 vote

QGIS Trigger Defaults Immediately in Python Console

You could modify your script slightly so that, if there are any existing features in your layer, the "Lon" and "Lat" fields are populated with their x and y values first, then set ...
  • 15.8k
0 votes

PyQGIS: how to raster an image with the reference coordinate points

Assuming you have ground control points in some known coordinate reference system, and assuming you have the pixel coordinates in those images that show the ground control points you can use the ...
  • 7,587
0 votes
Accepted

Changing the layer name in Legend for QGIS Print Layout with Python

It turns out my previous answer was still just a workaround, and if I edited the legend afterwards, it would realize as much and reset itself. Alas, here is the actual solution, with heavy inspiration ...
  • 81
2 votes
Accepted

Loading Shapefiles with addMapLayer() in PyQGIS does not display them until restart of QGIS

The QgisInterface.addVectorLayer() method, as well as returning a QgsVectorLayer object, also adds the layer to the project. So you are doing this twice using two different methods. I suggest changing:...
  • 15.8k
3 votes
Accepted

How to display the attribute value in an information window?

If the attribute you are trying to access is in your layer A/layer1, then you already have a reference to the feature and you can access its 'geo_parcelle' attribute with feature['geo_parcelle'] and ...
  • 15.8k
0 votes

Accessing WFS data through proxy in QGIS

I ran into a similar problem to this and couldn't get the QgsNetworkAccessManager to work. Used this instead: from PyQt5 import QtNetwork ##Proxy Setting via QtNetwork proxy = QtNetwork....
  • 1
0 votes

PyQGIS: the requests library fails to handle proxies

I ran into a similar problem to this and couldn't get the QgsNetworkAccessManager to work. Used this instead: from PyQt5 import QtNetwork ##Proxy Setting via QtNetwork proxy = QtNetwork....
  • 1
1 vote

Zip output of QGIS Processing Algorithm

I forgot to answer my question. I found a "decent" solution with ppa: def postProcessAlgorithm(self, context, feedback): path = 'your path url here' for elem in self....
2 votes

Changing the layer name in Legend for QGIS Print Layout with Python

Looks like you already got a working solution, but here is another approach- passing the layer tree layer object, the index of the root node and the desired label as a string to the ...
  • 15.8k
2 votes

Changing the layer name in Legend for QGIS Print Layout with Python

After trying it out for a few hours, I finally figured it out. I was on the right path with QgsLayerTreeLayer, however, I was editing the wrong object - basically, still the vector layer itself rather ...
  • 81
1 vote

Create a polygon from WKT format in PyQGIS

I think you can use the Plugin QuickWKT Go to the Plugins -> Manage and Install Plugins.. Install QuickWKT Open the plugin QuickWKT Select polygon from WKT Click OK and you will your Polygon If ...
0 votes

How to delete duplicate based on field value?

You can use this snippet if the value of identifica is only duplicated once: # Your layer layer = iface.activeLayer() value to delete = 'Utiliteit' # List of features id to remove after the test ...
  • 1,407
4 votes
Accepted

PyQGIS - If else statement

... def processAlgorithm(self, parameters, context, feedback): option = self.parameterAsEnum(parameters, self.RAD_PERCENTAGE, context) if option == 0: # More than 10 years ... elif ...
0 votes

Fixing "ImportError: No module named qgis.core"?

I tried to write a stand alone python script to use QGIS and encountered the same issue. I was using Ubuntu 20.04 and the QGIS version was version 3 family. The solution was: import sys sys.path....
  • 1
2 votes
Accepted

Python action to find out if selection made in one layer is inside polygon in another layer

Try this with QgsVectorLayer.aggregate() layer1 = QgsProject.instance().mapLayersByName('layer1')[0] # I just prefer this style for testing... layer2 = QgsProject.instance().mapLayersByName('layer2')[...
  • 27.3k
1 vote
Accepted

PyQGIS: How to load raster file from memory output

Your problem is 'OUTPUT':'memory:'. To create a memory layer for the output of an intermediate processing step you should use either QgsProcessing.TEMPORARY_OUTPUT or just 'TEMPORARY_OUTPUT'. Both of ...
  • 15.8k
4 votes

Releasing PyQGIS file locks?

Anyone else finding this that still encounters a similar error - There are multiple file locks that all need to be removed. If I wanted to delete a file after the process was done with it, I had to ...
  • 81
1 vote
Accepted

Batch saving multiple rendered images in QGIS

This will export all rasters added to the map as rendered. I want JPEG compression so I added COMPRESS=JPEG import os outfolder = r'C:\GIS\data\DEM50m' for layer in QgsProject.instance().mapLayers()....
  • 55.3k
0 votes
Accepted

PyQGIS: Add threshold value based on user input in Raster Calculator

Don't use 'INPUT_B' parameter as that is for additional raster inputs. The simplest way to insert the value of your threshold input parameter into the raster calc expression is to use Python string ...
  • 15.8k
0 votes
Accepted

Setting the alpha channel value of the colour of selected features using PyQGIS

You can use the .fromRgb() method of the QColor object, e.g.: >>> iface.mapCanvas().setSelectionColor( QColor().fromRgb(255,0,0,255) ) Obviously, this will give the same as the red color ...
  • 7,093
2 votes
Accepted

Use QGIS processing parameter in field calculator's formula

The 'FORMULA' key in the dictionary of parameters passed to QgisRun gets a string as value. In your example that is the verbatim ' "MyFieldName" * parameters[self.Lane_Weight] '. When ...
  • 8,847
1 vote

Processing script to load raster layer from PostGIS

Thank you @til_b for your help. I tried to add the argument to the QgsProcessingContext.LayerDetails call as you suggested, but it didn't change the error. I tried several other things, and I finally ...
1 vote

Processing script to load raster layer from PostGIS

The constructor to QgsProcessingOutputRasterLayer takes only two arguments. See https://qgis.org/pyqgis/3.26/core/QgsProcessingOutputRasterLayer.html . Remove the QgsProcessing.TypeRaster argument ...
  • 3,707
0 votes

QgsRasterFileWriter.writeRaster() is crashing python program

I would recommend adding QgsApplication at the beginning of the code when using Qgis qgs = QgsApplication([], False) QgsApplicationsetPrefixPath.setPrefixPath("{path to qgis}/qgis", True) ...
1 vote
Accepted

Add new field with a specific data type in QGIS 3

You can just create a conversion dict to convert from text (or the index) of the combobox to the QVariant equivalent class X: CONVERSION_TYPE = { "Int": QVariant.Int, &...
5 votes
Accepted

PyQGIS autoincrement id field

Firstly, regarding the errors you are getting. Here you are storing the layer Data Provider object in the pr variable: pr = vl.dataProvider() Then in these lines: pr.dataProvider().addAttributes(...
  • 15.8k
2 votes

How to use the array_length() field calculator expression in PyQGIS

I am not sure what the wider context of your question is, but you can use expressions in QGIS like so: layer.selectByExpression(expression) This may mean that you can use your expression like so: ...

Top 50 recent answers are included