3

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?

2

Add render.waitForFinished() after render.start()

def finished():
    img = render.renderedImage()
    img.save(image_location, "png")

render.finished.connect(finished)
render.start()
render.waitForFinished()

Or

render.start()
render.waitForFinished()
img = render.renderedImage()
img.save(image_location, "png")
3
  • very nice and simple and it worked! Thank you! – Till B Mar 25 '20 at 14:55
  • but out of curiosity, do you know why that line is needed in a standalone script, but not in the QGIS Python console? – Till B Mar 25 '20 at 15:08
  • I guess it is about paralel/asyncron programming issue. I've no experience on that. – Kadir Şahbaz Mar 25 '20 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.