Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
QGIS 3 standalone application sample
# Code borrowed from https://subscription.packtpub.com/book/application_development/9781783984985/1/ch01lvl1sec18/creating-a-standalone-application
# and upgraded for QGIS 3.0
import os
import sys
import shutil
import tempfile
import urllib.request
from zipfile import ZipFile
from glob import glob
from qgis.core import (QgsApplication, QgsCoordinateReferenceSystem, QgsFeature,
QgsGeometry, QgsProject, QgsRasterLayer, QgsVectorLayer)
from qgis.gui import QgsLayerTreeMapCanvasBridge, QgsMapCanvas
from qgis.PyQt.QtCore import Qt
# Unused so commented
# from qgis.PyQt.QtGui import *
app = QgsApplication([], True)
# On Linux, didn't need to set it so commented
# app.setPrefixPath("C:/Program Files/QGIS Brighton/apps/qgis", True)
app.initQgis()
canvas = QgsMapCanvas()
canvas.setWindowTitle("PyQGIS Standalone Application Example")
canvas.setCanvasColor(Qt.white)
crs = QgsCoordinateReferenceSystem(3857)
project = QgsProject.instance()
canvas.setDestinationCrs(crs)
urlWithParams = 'type=xyz&url=https://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857'
rlayer2 = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'wms')
if rlayer2.isValid():
project.addMapLayer(rlayer2)
else:
print('invalid layer')
# Download shp ne_10m_admin_0_countries.shp and associated files in the same directory
url = "https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/cultural/ne_10m_admin_0_countries.zip"
if not glob("ne_10m_admin_0_countries.*"):
with urllib.request.urlopen(url) as response:
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
shutil.copyfileobj(response, tmp_file)
with ZipFile(tmp_file.name, 'r') as zipObj:
# Extract all the contents of zip file in current directory
zipObj.extractall()
layer_shp = QgsVectorLayer(os.path.join(os.path.dirname(__file__), "ne_10m_admin_0_countries.shp"), "Natural Earth", "ogr")
if not layer_shp.isValid():
print("Layer failed to load!")
project.addMapLayer(layer_shp)
print(layer_shp.crs().authid())
print(rlayer2.crs().authid())
canvas.setExtent(layer_shp.extent())
canvas.setLayers([rlayer2, layer_shp])
canvas.zoomToFullExtent()
canvas.freeze(True)
canvas.show()
canvas.refresh()
canvas.freeze(False)
canvas.repaint()
bridge = QgsLayerTreeMapCanvasBridge(
project.layerTreeRoot(),
canvas
)
def run_when_project_saved():
print('Saved')
project.projectSaved.connect(run_when_project_saved)
project.write('my_new_qgis_project.qgz')
def run_when_application_state_changed(state):
print('State changed', state)
app.applicationStateChanged.connect(run_when_application_state_changed)
exitcode = app.exec()
QgsApplication.exitQgis()
sys.exit(exitcode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment