2

I'm trying map rendering with stand alone script, so I have small script which works fine in python console provided QGIS, however when I run same code in stand-alone script it executes without error, but output is not produced.

Here is my standalone script:

from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtXml import *

QgsApplication.setPrefixPathddd("C:\Program Files (x86)\QGIS Valmiera", True)

QgsApplication.initQgis()

mapinstance = QgsMapLayerRegistry.instance()
mapinstance.removeAllMapLayers()

layer = QgsVectorLayer("F:\scripts\map\wb.shp", "test", "ogr")

if layer.isValid():
    print "shplayer succesfully loaded - adding to mapinstance"
    mapinstance.addMapLayer(layer)
else:
    print "shplayer failed to load!"

print mapinstance.mapLayers()

# create image
img = QImage(QSize(800,600), QImage.Format_ARGB32_Premultiplied)
# set image background color
color = QColor(255,255,255)
img.fill(color.rgb())
# create painter
p = QPainter()
p.begin(img)
p.setRenderHint(QPainter.Antialiasing)
render = QgsMapRenderer()
# set layer set
lst = [ layer.id() ] # add ID of every layer
render.setLayerSet(lst)
# set extent
rect = QgsRectangle(render.fullExtent())
#rect.scale(1.39800703)
rect.scale(1.1)
render.setExtent(rect)
# set output size
render.setOutputSize(img.size(), img.logicalDpiX())
# do the rendering
render.render(p)
p.end()

# save image
img.save('F:\scripts\out.png',"png")    

QgsApplication.exitQgis()
2

You need to add in a variable for the QgsApplication. Try changing the beginning to this:

QgsApplication.initQgis()
app = QgsApplication([], True)

Adding the app variable should fix your problem.

Rendering and Labeling Shapefile with PyQGIS

How to use map composer in a stand-alone script?

  • Thanks for your reply. I have added those line to my code, however its giving me error "shape layer failed to load!". I did checked shape file path and its seems to be correct. Plz help. – roony Mar 12 '14 at 12:03
  • Is "test" a valid column attribute for that shapefile? – midfield99 Mar 12 '14 at 14:08
  • And this looks like there are some typos: QgsApplication.setPrefixPathddd You will have trouble osgeo-org.1560.x6.nabble.com/… layers if the prefix path is bad. – midfield99 Mar 12 '14 at 14:15
  • "test" is not attribute of shape file, I think its user defined name as given in PyQGIS developer cookbook. also I have removed typo error of setPrefixPath, still getting same error... – roony Mar 12 '14 at 15:16
  • 1
    I made changes to path "C:/Program Files/QGIS Valmiera/apps/qgis" . It's working fine.. thanks :) – roony Mar 12 '14 at 19:00

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.