Skip to content

Instantly share code, notes, and snippets.

@ThomasG77
Last active March 2, 2019 18:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasG77/5372e1b9406e018081fe8ed350e496fd to your computer and use it in GitHub Desktop.
Save ThomasG77/5372e1b9406e018081fe8ed350e496fd to your computer and use it in GitHub Desktop.
# Code borrowed from https://subscription.packtpub.com/book/application_development/9781783984985/1/ch01lvl1sec18/creating-a-standalone-application
# and upgraded for QGIS 3.0
import sys
from qgis.core import (QgsApplication, QgsFeature, QgsGeometry,
QgsProject, QgsVectorLayer)
from qgis.gui import 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)
layer = QgsVectorLayer('LineString?crs=epsg:4326', 'MyLine' , "memory")
pr = layer.dataProvider()
linstr = QgsFeature()
geom = QgsGeometry.fromWkt("LINESTRING (1 1, 10 15, 40 35)")
linstr.setGeometry(geom)
pr.addFeatures([linstr])
layer.updateExtents()
QgsProject.instance().addMapLayer(layer)
canvas.setExtent(layer.extent())
canvas.setLayers([layer])
canvas.zoomToFullExtent()
canvas.freeze(True)
canvas.show()
canvas.refresh()
canvas.freeze(False)
canvas.repaint()
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