New answers tagged

0 votes

How to Select Layer by Location of Feature in PYQGIS?

Less code and a more readable version: for feature in intersect_layer.getFeatures(): sql_expression = f''' fid = {feature.id()} ''' intersect_layer.setSubsetString(sql_expression) # This ...
user avatar
  • 5,642
0 votes

PyQGIS Problems Update to 3.24.3 with Qt Library 5.15.3

I resolve uninstalling this library: pip uninstall pyqt5-qt5
user avatar
  • 622
0 votes

'QGIS Processing Executor'_Issue: "sqlite3_open ... unable to open database file"

Looking at this: ERROR 4: sqlite3_open('C:/zz_QGIS_Test_SHPs/result.shp'.gpkg) failed: unable to open database file, IMHO, there are two things wrong: Why is there an attempt to "open" a ...
user avatar
  • 1,286
2 votes

QgsVectorFileWriter write kml qgis-3 with sybmology

There are some classes and methods you are using which don't even exist in QGIS3: QgsFillSymbolV2 should be just QgsFillSymbol and likewise rendererV2() is just renderer() QgsVectorFileWriter....
user avatar
  • 1,454
1 vote

Separating comma-separated text using PyQGIS

If you want to extract the coordinates from text you could use a python regex: text = "latitude: 42.800392, longitude: 24.229796" coordinates = re.findall('\d*\.?\d+',text) coordinates[0] ...
user avatar
  • 1,439
0 votes

Raster Calculator in processing scripts crashes using PyQGIS

I get a similar crash but it works when I remove the use of QgsProcessingMultiStepFeedback in the process.
user avatar
2 votes
Accepted

Editing a QGIS script to use field values as input parameters rather than introducing a constant value

Based on your comments you can use this modified script: from qgis.core import QgsProcessing, QgsProcessingAlgorithm, QgsProcessingMultiStepFeedback, QgsProcessingParameterFeatureSource, ...
user avatar
  • 24.9k
1 vote

PyQGIS: moving legend with changed reference point

From your screenshot, it is clear that your legend is being added to your layout, "except for being in the wrong place". You haven't shown or explained how you calculated the layout point ...
user avatar
  • 13.6k
1 vote

Adding a fixed table to layout in QGIS

Late to the party but an answer composerTitle = 'Layout 1' project = QgsProject.instance() projectLayoutManager = project.layoutManager() # Access to the layout by name layout = projectLayoutManager....
user avatar
  • 28.6k
2 votes
Accepted

How can I activate GeoTIFF compression in QGIS 3.x gdal_translate?

Try 'OPTIONS':'COMPRESS=JPEG|JPEG_QUALITY=60' I executed the tool manually in QGIS, pressed Ctrl+Alt+H to see the command syntax:
user avatar
  • 51.4k
5 votes
Accepted

Displaying milliseconds in Attribute Table using PyQGIS

The comment by @Matt was already pointing in a correct direction. QgsDateTimeFieldFormatter is indeed needed to modify the display of DateTime values. The following code example replaces the default ...
user avatar
  • 1,454
0 votes

Looking for manual on how to properly setup standalone PyQGIS without GUI

Finally, I got a solution to be able to run the "standalone PyQGIS"* example "Proximity" (above mentioned by "Mar Tijn" and provided by "MarByteBeep). This ...
user avatar
0 votes
Accepted

PyQGIS script (.py) runs correctly on Windows but not on Mac

I found a solution, even if it doesn't solve all my doubts. The mac computer does not seem to recognise the relative path given, in any of the tried formulations (".\", ".", "....
user avatar
  • 47
3 votes

Making automatic updated date and time field in QGIS

Create a new date or datetime field. Go to the layer properties › Attributes Form. Select your field. Activate the checkbox Apply default value on update and set the Default value to $now.
user avatar
  • 151
1 vote

Maximum value of field of vector layer using PyQGIS

There are also several other approaches available: Approach 1 : QgsAggregateCalculator with Max Available aggregates to calculate. Not all aggregates are available for all field types. This approach ...
user avatar
  • 23k
1 vote

Using PyQGIS to buffer the width different than the height of a rectangle

Here a PyQGIS solution for 1 feature : from functools import lru_cache @lru_cache(maxsize=6) def orientation_choices(num_coords: int, axis: str = "x") -> list: if axis == "x&...
user avatar
  • 11.8k
2 votes
Accepted

Creating Virtual Field from QGIS Python Console

Try to get the addExpressionField from the QgsVectorLayer class with this: from qgis.utils import iface from qgis.core import QgsVectorLayer, QgsField try: from PyQt5.QtCore import QVariant except ...
user avatar
  • 23k
2 votes
Accepted

Using PyQGIS to displace polygon to larger intersection

Try this approach, it will move the small feature to the largest overlapping features centroid: def nameToLyr(layername): """Outputs a layer from a layername input""" ...
user avatar
  • 51.4k
2 votes

Requests Python module in QGIS return nontype or empty CSV

Your code should work. I can't run/reproduce your code without an API key for the particular API you were using. I used the geonames.org API for a test. In your screenshot, it looks like your file is ...
user avatar
  • 1,286
5 votes

QgsPoint invalid argumets in PyQGIS 3

vertexAt method returns QgsPoint. So, you don't need to construct new one. You get the error since QgsPoint class doesn't have any constructor method which takes a QgsPoint argument in QGIS 3 unlike ...
user avatar
6 votes
Accepted

Getting all shapefile layers in project using PyQGIS

The shapefile format is a geospatial vector data format, therefore on a first stage I suggest to catch all of vector layers with the QgsVectorLayer class. There are several approaches to achieve it ...
user avatar
  • 23k
3 votes
Accepted

Conditional signals in QgsTask managing algorithm output

Try the example below. Sorry, your code was a bit of a mess, I basically tried to make it functional in the quickest way that I could. I suggest to now study the code and do your own research and self ...
user avatar
  • 13.6k
0 votes
Accepted

How to create 3D polygon layer in QGIS 3 or convert 2D layer to 3D similar to PostGIS function ST_Force3d()

Ok I was able to solve this by using this code when saving to file: QgsVectorFileWriter.writeAsVectorFormat(inputlayer, str(outputlayer), "utf-8", QgsCoordinateReferenceSystem("EPSG:...
user avatar
  • 75
0 votes
Accepted

Issue when running refactorfields from the python console

The parameters of a processing algorithm must be a dictionary, for example: processing.run("native:refactorfields", {'INPUT': input, 'FIELDS_MAPPING': [{'name':"NEWID", 'type':0, '...
user avatar
  • 1,385
2 votes
Accepted

Setting direction to clockwise using PyQGIS

QGIS Diagram settings way : ds = QgsDiagramSettings() # counter-clockwise direction ds.setDirection(QgsDiagramSettings.Counterclockwise) # clockwise direction ds.setDirection(QgsDiagramSettings....
user avatar
  • 11.8k
1 vote
Accepted

pyqgis 3 zoom to selected polygon without zooming in so far

I created a quick script with the setCenter method from the QgsMapCanvas class. It allows you to change the extent of the canvas without changing zoom level. It works with Polygons, Lines and Points. ...
user avatar
  • 1,385
2 votes
Accepted

Looking for QGIS processing script equivalent of ST_Buffer

As you are mentioning SQL ST_Buffer, I will pretend you are using PyQGIS. At the layer level, you can use QGIS Processing. import processing processing.run("qgis:buffer", # get the list of ...
user avatar
  • 5,665
4 votes
Accepted

Sharing class variables across thread (QgsTasks) with pyQGIS

Here is working example. I have modified your code a bit. Because both your tasks have much the same function (to run a processing algorithm and return a result layer) I would prefer to only create ...
user avatar
  • 13.6k
4 votes

Transform CRS and strip decimal places

To avoid rounding the result, you can simply define the field length accordingly. So if you define Output field precision to 6, all numbers will be automatically rounded to 6 digits. Use Menu ...
user avatar
  • 40.1k
3 votes

Transform CRS and strip decimal places

One can try one of the following expressions: format_number(y(transform($geometry,'EPSG:3857','EPSG:4326')),6) It uses the format_number(number, [places=0], [language]) function: Returns a number ...
user avatar
  • 23k
2 votes
Accepted

Get M-value from shapefile by mouse click on canvas

There are two main issues with your code. First one is that QgsMapToolIdentify.identify() will return a list of identified features. So you will need index your result variable before accessing any ...
user avatar
  • 1,454
1 vote
Accepted

Pyqgis 3 adding polygon vector layer in code and triggering iface.actionAddFeature().trigger() will give me polygons but they cannot be selected

Regarding your first problem I can only assume that you forgot to commit your changes to the underlying data provider. This could be an issue if you iterate through each feature and zoom to it's ...
user avatar
  • 1,454
5 votes
Accepted

Running function from double click with PyQGIS

I'll just add my recent answer from this question to this post. See the linked answer for a brief explanation, I just changed the event type to filter for double clicks. class MouseClickFilter(QObject)...
user avatar
  • 1,454
2 votes

Updating attribute field with values from list calculation using PyQGIS

Try this logic: a = [134.24, 134.24, 134.24, 134.99] b = [58.848430067837946, 70.46615125391358, 63.02756211443306, 60.662300968221174] c = 0.6673779977746334 newlayer = iface.activeLayer() with ...
user avatar
  • 24.9k
1 vote

Debugging Error: Algorithm gdal:dissolve not found in PyQGIS

To check whether PyQGIS has a certain algorithm one can use the following code: from qgis import processing for alg in QgsApplication.processingRegistry().algorithms(): if 'dissolve' in alg.id(): ...
user avatar
  • 23k
1 vote
Accepted

QgsAttributeForm disappears using it in a QGIS plugin

Within the plugin class you need to store the QgsAttributeForm object as an instance variable instead of using a local variable. This is needed because as soon as the method finishes its execution, ...
user avatar
  • 1,454
1 vote

Adding missing python packages to QGIS Plugin?

The place were the blessed route to a solution will be, if it can be found, is PIP dependencies for Python plugins QGIS enhancement proposal. It's a hard problem to solve. That thread contains ...
user avatar
  • 27.5k
2 votes
Accepted

Get coordinates on click without using QgsMapToolEmitPoint

One way to get the coordinates regardless of the selected tool is using an Event Filter to intercept the mouse events of the QgsMapCanvas object. Within the event filter function there is a check for ...
user avatar
  • 1,454
4 votes
Accepted

Setting up thread with busy progress indicator or GIF in PyQGIS

As in my answer in the post you linked, I create a QgsTask MyTask with a layer parameter. I just adapt the content of your method buffering in the run method of the QgsTask. I defined 2 signals (...
user avatar
  • 11.8k

Top 50 recent answers are included