I have an existing QGIS project and I want to write a standalone Python script that outputs a png file of the map. I work on Windows 10. This is the code that I use (basically taken from the PyQGIS cookbook):
import os
from qgis.core import *
from PyQt5 import *
from PyQt5.QtSvg import *
from PyQt5.Qt import *
app = QgsApplication([], True)
app.setPrefixPath(r"C:/Program Files/QGIS 3.10/apps/qgis", True)
app.initQgis()
project = QgsProject.instance()
project.read("filename.qgz")
layer = project.mapLayersByName("myLayer")[0]
options = QgsMapSettings()
options.setLayers([layer])
options.setBackgroundColor(QColor(255, 255, 255))
options.setOutputSize(QSize(800, 600))
options.setExtent(layer.extent())
render = QgsMapRendererParallelJob(options)
image_location = os.path.join(os.getcwd(), "render.png")
def finished():
img = render.renderedImage()
img.save(image_location, "png")
print("saved")
render.finished.connect(finished)
render.start()
Executing these commands line by line in the Python console inside QGIS works perfectly fine and it outputs a png file with the map in a fraction of a second. However running this from the Python interpreter, it does not output anything. When calling render.isActive()
, it returns True
.
Is this a bug? Or do I have to do things differently when I want to render a map in a standalone script?