QGIS is a useful GIS opensource software which offers many ways of views and analyze geospatial data.
However analysis tools and basic functionalities may be not enough for specific needs, or when tasks need to be automated or easier to use.
PyQGIS is an API which allows us to code in python in QGIS and manipulate many functionalities.
This library is however so wide that it is difficult to know how to get started.
This post is a first step to get started with PyQGIS, from very basic commands.
Python console open usually at the bottom of QGIS frame
print("some_result") to display a result
By launching the following command on python console, Current scale of map canvas can be retrieved.
With the following command launched on python console, map canvas can be set to
Above commands looks not intuitive at a first view, but Python console of QGIS allows us to investigate commands components easily.
For example if we inquiry only
Console will return
<qgis._gui.QgsMapCanvas object at 0x1ac03ab80>
which means that
iface.mapCanvas() is a
QgsMapCanvas object of PyQGIS.
QgsMapCanvas pyqgis on your favorite search browser, you'll get documentation of this class,
and have access of all methods that
iface.mapCanvas() is able to do.
Thus, you can try many of methods of QgsMapCanvas class.
Here are two examples:
3.1. center to retrieve center point of map canvas
iface.mapCanvas().center() <QgsPointXY: POINT(454338.46291687525808811 5845991.44166376255452633)>
3.2. extent where canvas extent can be retrieved
iface.mapCanvas().extent() <QgsRectangle: 452382.75110932614188641 5845268.24721858091652393, 456294.17472442437428981 5846714.63610894419252872>
Python console of QGIS is very useful to understand PyQGIS.
By launching first commands, and inquiry commands prefixes such as
iface.mapCanvas(), you can discover a PyQGIS class (here
QgsMapCanvas) and the wealth of methods it offers.
PyQGIS is a very wide library, and understand its architecture becomes easier by inquiring a class like above on the Python Console of QGIS, and discover methods on documentation.
Next post will focus on dealing with layers with pyQGIS
iface.mapCanvas(), you surely wondered what
iface means. By the same approach we used on this post, you can run
iface command, it will return the QgisInterface class and many many related methods.
# iface() with ()does not work iface <qgis._gui.QgisInterface object at 0x15589fe50>