31
votes
Accepted
Getting layer extent using 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 ...
21
votes
Accepted
Loading style (*.qml file) to layer via PyQGIS
I have my qml styles in a fix path (c:/pyqgis_data/Styles/). So, to load arrows_red_orange.qml (exclusively for point layers), next lines at the Python Console of QGIS work:
>>>layer = ...
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()]
18
votes
Accepted
Clearing QGIS Python console with pyQGIS
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 ...
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 ...
11
votes
Getting layer extent using 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 ...
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 ...
11
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
...
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
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 ...
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 ...
9
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 ...
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. ...
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 ...
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 (...
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()....
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 = ...
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(),'...
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"
...
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 ...
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 ...
6
votes
Clearing Python console in QGIS
In QGIS version 3.22, there is a button on the top left of the console that clears it.
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 ...
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 ...
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 ...
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 ...
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 ...
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(&...
6
votes
Accepted
Refreshing map canvas in for loop in QGIS 3
I see that your request is for the canvas, but it seems the ultimate goal is a file based output, so I'll answer that one instead.
You don't need to update the canvas itself. You can also very well do ...
6
votes
Accepted
Creating rectangles from CSV coordinates via Python console in QGIS
You can use the following structure. For other rectangles, add the highlighted lines (between ###) to a for loop.
layer = QgsVectorLayer("Polygon?crs=EPSG:2193", "Polygons", "...
Only top scored, non community-wiki answers of a minimum length are eligible
Related Tags
qgis-python-console × 198pyqgis × 140
qgis × 73
qgis-3 × 32
python × 29
qgis-plugins × 17
qgis-processing × 16
raster × 13
fields-attributes × 6
pyqgis-3 × 6
print-composer × 5
raster-calculator × 5
shapefile × 4
attribute-table × 4
qgis-2 × 4
qgis-modeler × 4
grass-gis × 4
coordinate-system × 3
gdal × 3
field-calculator × 3
layers × 3
export × 3
csv × 3
error × 3
import × 3