The iface
class used in the preceding snippets is important in every PyQGIS code; it is used to access most graphical QGIS components, from displayed layers to the toolbar buttons.
The iface
class is a Python wrapper for the C++ class, QgisInterface
, which is documented at http://qgis.org/api/classQgisInterface.html. Most QGIS classes have a Qgs
prefix. Some special classes can have the Qgis
or QGis
prefixes.
The prefix Qgs
is the Qt
namespace registered by Gary Sherman, the QGIS creator, so Qt (Q) and Gary Sherman (gs).
The most common use of the iface
class is to get a reference of the canvas
where maps are displayed:
canvas = iface.mapCanvas()
The class can also be used as a shortcut to load raster or vector layers; for example loading the raster, path/to/my/raster.tif
, and naming it myraster
in the legend panel. This can be done by typing the following command:
iface.addRasterLayer("path/to/my/raster.tif", "myraster")
Pay attention to writing paths with Windows. A path string, such as C:path o
aster.tif
, has the special escape character, , so rewrite it by double escaping
C:\path\to\raster.tif
or using the Unix notation, C:/path/to/myraster.tif
, or notify Python with a raw string adding an r
as in r"C:path o
aster.tif"
. Generally, it's good practice to create path strings using a Python library like os.path
.
QGis
is another class that contains some useful constants, such as a QGIS version or some default values. We can find out the QGIS version name running on our system by typing in the following command:
print QGis.QGIS_RELEASE_NAME, QGis.QGIS_VERSION_INT
For example, if the output is Chugiak 20400
, then this value represents the version name and the version integer representation (which is version 2.4). This is useful to programmatically create a plugin that can run on different QGIS versions. The following snippet helps to distinguish the code among them:
if Qgis.QGIS_VERSION_INT < 20400: <here the code compatible with older version> else: <here the code compatible with version higher or equal to 2.4>
18.188.218.184