30 votes
Accepted

Getting layer extent in PyQGIS?

The answer is almost completely contained in a post I recently wrote. The extent is returned as a QgsRectangle() object with the following code: layer = iface.activeLayer() # load the layer as you ...
mgri's user avatar
  • 16.1k
21 votes
Accepted

"AttributeError: 'QgisInterface' object has no attribute 'legendInterface'" in PyQGIS 3

You could just replace layers = iface.legendInterface().layers() with layers = [layer for layer in QgsProject.instance().mapLayers().values()]
Joseph's user avatar
  • 75.3k
12 votes
Accepted

Clearing Python Console in QGIS using Python Command

QGIS offers you several classes for logging messages into the Log Messages Panel (i.e., no need to print debug messages from your plugin into the QGIS Python console). You could even easily create a ...
Germán Carrillo'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
11 votes

"AttributeError: 'QgisInterface' object has no attribute 'legendInterface'" in PyQGIS 3

The equivalent of layers = self.iface.legendInterface().layers() in QGIS 3 is layers = [tree_layer.layer() for tree_layer in QgsProject.instance().layerTreeRoot().findLayers()] This recursively ...
AleksMat's user avatar
  • 416
10 votes

Getting layer extent in PyQGIS?

you were on the right track you just need to go a step further. See the QGIS documentation for QgsRectangle Basically, you do: get the current Layer layer = iface.activeLayer() get the extent ...
LaughU's user avatar
  • 4,146
10 votes
Accepted

Calling Rotate Feature tool from QGIS Python Console

Use this script: # Get all actions actions = iface.mainWindow().findChildren(QAction) # Check the action action = [x for x in actions if x.objectName()=='mActionRotateFeature'][0] # Run the action ...
Kadir Şahbaz's user avatar
10 votes
Accepted

Removing extra space at top of the legend in print composer from Python console in QGIS

You can use rstyle method of legend. You can set spacing using setMargin function. Documentation for rstyle and setMargin. legend.rstyle(QgsLegendStyle.Title).setMargin(1) # 1 mm
Kadir Şahbaz's user avatar
9 votes
Accepted

Deleting variables from the Python Console in a programmatic way?

In addition to @bcollins answer, if you want to change your variables you have defined inside the QGIS python console you can try this approach: Define a variable which holds all variables before you ...
LaughU's user avatar
  • 4,146
9 votes
Accepted

QGIS: Is there a way to make the "Python Console" a separate window?

You can show a new window using the following from console.console import PythonConsoleWidget consoleWidget = PythonConsoleWidget() consoleWidget.show() You could hide with startup.py original ...
ThomasG77's user avatar
  • 30.3k
8 votes
Accepted

Shortcuts in QGIS's Python Editor

In theory, there is already a shortcut for running PyQGIS scripts from the Python Editor. It is Ctrl + Shift + E (for the Run Selected action, it is Ctrl + E). Unfortunately, in my OS (Ubuntu), the ...
Germán Carrillo's user avatar
8 votes

Invalid syntax in expression using PyQGIS

You can use Python f-string syntax for the expression. Use ex1 = QgsExpression(f"(mean - {min1}) / ({max1} - {min1})") Python f-string is the newest Python syntax to do string formatting. ...
Kadir Şahbaz's user avatar
8 votes
Accepted

Simple PyQGIS code working in QGIS python console but not in Python plugin

What you are referring to here as a plugin is a custom processing algorithm script. This in itself is not a plugin, though it could be added to a 3rd party provider as part of a processing plugin (and ...
Ben W's user avatar
  • 20.6k
7 votes
Accepted

Getting position of point in PyQGIS?

#active layer is a point layer: feat = next(iface.activeLayer().getFeatures())#get first feature geo= QgsGeometry.asPoint(feat.geometry())#get the geometry of the feature pxy=QgsPointXY(geo) print (...
The Rabbit's user avatar
7 votes
Accepted

Loading GeoDataFrame as QGIS vector layer without exporting to shapefile

You can use the following import geopandas countries_gdf = geopandas.read_file("ne_10m_admin_0_countries.shp") vl = QgsVectorLayer(countries_gdf.to_json(),"mygeojson","ogr") QgsProject.instance()....
ThomasG77's user avatar
  • 30.3k
7 votes

Invalid syntax in expression using PyQGIS

You need to format your expression : expression = '( ( "mean" - {min1} ) / ( {max1} - {min1} ) )'.format(min1=min1, max1=max1) print(expression) # To let's you check what you have ex1 = ...
etrimaille's user avatar
  • 7,130
7 votes
Accepted

QGIS save selected layers to shapefiles by python console

Driver name parameter should be 'ESRI Shapefile' instead of 'SHP' for shapefiles. And no need layerOptions here. Change QgsVectorFileWriter.writeAsVectorFormat( lyrs,SHPpath,'utf-8',lyrs.crs(),'...
Kadir Şahbaz's user avatar
7 votes

QGIS save selected layers to shapefiles by python console

and in addition to Kadir: you should use writeAsVectorFormatV3 since QGIS Version 3.20. The code then looks like for lyrs in iface.layerTreeView().selectedLayers(): path = "C:/tonne/test" ...
eurojam's user avatar
  • 9,799
6 votes

Zooming from python console of QGIS

All the zoom options under the 'View' menu can be executed in the python console by the following code. eMenu = self.iface.viewMenu() eMenu.actions() [index].trigger() Replace the "index" with the ...
Sjs's user avatar
  • 997
6 votes
Accepted

Calling interpolation plugin from Python console of QGIS

I was able to provide a full solution in the following question: How to compute an interpolation raster from the python console in QGIS? I will repost the answer here as well, because of the large ...
root676's user avatar
  • 2,375
6 votes
Accepted

Print values from Tables in QGIS Console

You need to access the attributes of the features of the table. lyr = iface.activeLayer() features = lyr.getFeatures() for ft in features: attrs = ft.attributes() print attrs To access ...
Jakob's user avatar
  • 7,451
6 votes

Deleting variables from the Python Console in a programmatic way?

There are a couple of builtin functions you should consider for this. dir() will gives you the list of in scope variables globals() will give you a dictionary of global variables locals() will give ...
bcollins's user avatar
  • 3,543
6 votes

Deleting variables from the Python Console in a programmatic way?

A method which I used a while ago was to begin each variable name with an underscore ("_"). As there are no other variables beginning with a single underscore (only double), you can search for all ...
Joseph's user avatar
  • 75.3k
6 votes
Accepted

When PyQGIS script is run through console layer does not load successfully

First of all, you should review Using PyQGIS in standalone scripts for further information. Also, try to run "OSGeo Shell" as @Oscar states. According to the documentation, you need to ...
Kadir Şahbaz's user avatar
6 votes

Python script output to console doesn't update beyond first page in QGIS

You generally shouldn't use print() for debugging this as the Python Console is not built to really help you here. The best advice is to use QgsMessageLog.logMessage as that will scroll with the ...
Nathan W's user avatar
  • 34.6k
6 votes
Accepted

Using Boolean Parameter in QGIS Graphic Modeler

In the model environment, some variables are created for each input parameter, which can be used by algorithms. The name of those variables is automatically assigned from the description of the ...
Gabriel De Luca's user avatar
6 votes

Making Voronoi polygons using Python Console of QGIS

Use full path for output. And I suggest you to use runandload method instead of runalg in this case. It adds the output to "Layers" panel. import processing output = processing.runandload(&...
Kadir Şahbaz's user avatar
6 votes
Accepted

Export Project to DXF dialog using Python

Does DxfLayer even support multiple inputs? No. The error QgsDxfExport.DxfLayer(QgsDxfExport.DxfLayer): argument 1 has unexpected type 'list' states that, explicitly. But you can use dxfExport....
Kadir Şahbaz's user avatar
6 votes

Adding points with coordinates delimited by commas from CSV file in QGIS Python Console

There are several things regarding your code: the uri for a CSV file must include the file:// prefix, as it is mentioned in the QGIS Documentation: The provider string is structured as a URL, so the ...
Taras's user avatar
  • 31.3k
5 votes
Accepted

Error running Grass module in Qgis python console

Usually when I run processes, I define the extent instead of leaving it blank (which often results in errors like you have shown). So you could use something like the following: # Define input and ...
Joseph's user avatar
  • 75.3k

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