I would like to use standalone appliction to apply .qml
style to a layer and use QgsMapRenderer()
to save it as image on a hard disk. The are a lot of questions like mine at this site and it seems that most of the issues emerge from settings for QgsApplication()
. Unfortunately it seems that I wasn't able to setup QgsApplication()
in a right way. My code is pretty standart rendering code from PyQGIS Cookbook that was used as a template in other questions like mine. It produces transparent .png inage with no layer rendered. Though this code works (without initialisation of QgsApplication()
) if I ran it line by line in QGIS console (QGIS 2.4).
So I have following QgsApplication()
settings (on Alt Linux).
Application state:
QGIS_PREFIX_PATH env var:
Prefix: /usr
Plugin Path: /usr/lib64/qgis
Package Data Path: /usr/share/qgis
Active Theme Name:
Active Theme Path: :/images/themes//
Default Theme Path: :/images/themes/default/
SVG Search Paths: /usr/share/qgis/svg/
User DB Path: /usr/share/qgis/resources/qgis.db
The code itself:
from qgis.core import *
from qgis.utils import *
from qgis.gui import *
from PyQt4.QtCore import QSize
from PyQt4.QtGui import QPainter, QImage, QColor
QgsApplication.setPrefixPath('/usr', True)
QgsApplication.initQgis()
print QgsApplication.showSettings()
lyr = QgsVectorLayer('test.shp', 'points', 'ogr')
lyr_id = lyr.id()
QgsMapLayerRegistry.instance().addMapLayer(lyr)
lyr.loadNamedStyle( 'test.qml')
# create image
img = QImage(QSize(800, 600), QImage.Format_ARGB32_Premultiplied)
# set image's background color
# color = QColor(255, 255, 255)
# img.fill(color.rgb())
# create painter
p = QPainter()
p.begin(img)
p.setRenderHint(QPainter.Antialiasing)
layers = QgsMapLayerRegistry.instance().mapLayers()
lst = layers.keys()
print 'lst', lst
renderer = QgsMapRenderer()
renderer.setLayerSet(lst)
extent = renderer.fullExtent()
rect = QgsRectangle(extent)
# print rect.toString()
rect.scale(1.1)
renderer.setExtent(rect)
# set output size
renderer.setOutputSize(img.size(), img.logicalDpiX())
# do the rendering
renderer.render(p)
p.end()
# save image
img.save('test.png', 'png')
QgsApplication.exitQgis()