Creating custom applications built on QGIS libraries¶
It is usually better to run processes automatically than manually. On our course(s), we are trying to promote this approach. While working with geospatial data using Fiona, RasterIO or GDAL libraries, it is no surprise that we can also use directly QGIS libraries.
Base module is qgis.core
, which is required by various tasks that
process data. With QGIS libraries, you can also create your own
application with graphical user interface. This can be achieved by
using module qgis.gui
, which enables many interesting options such
as map canvas, which we can use to display maps and so on.
Base structure of project¶
Before we start using QGIS libraries, we need to set up some settings for the start and the end of our script.
1#!/usr/bin/env python3
2
3# Minimalistic script, that initializes and prepares QGIS libraries
4# for use
5
6from qgis.core import *
7
8# But first, we have to setup a correct path to QGIS
9QgsApplication.setPrefixPath("/usr/local/", True)
10
11# Next, we create QGIS instance. Second argument will specify,
12# if we are creating app with graphical interface or not.
13qgs = QgsApplication([], False)
14
15# loading data sources
16qgs.initQgis()
17
18#
19# Here comes your code for app built on QGIS libraries.
20#
21
22# At the end of your program, you need to write exitQgis(). This command will deregister
23# data sources, providers and erase layers from computer memory.
24qgs.exitQgis()
After setting up permissions to launch file chmod 755
standalone.py
(Linux) we can safely launch it and leave it running.
Note
It is possible that you will need to set up correct
environmental variable PYTHONPATH
with path to Python
libraries for QGIS.