[Qgis-developer] vector layers loaded using pyQGIS not isValid()
Marco Lechner - FOSSGIS e.V.
marco.lechner at fossgis.de
Mon Apr 4 07:10:32 EDT 2011
Hi,
I'm trying to load several vector layers (shp and spatialite) using
PyQGIS but the Layers are never valid. what am I doing wrong? According
to http://www.qgis.org/pyqgis-cookbook/loadlayer.html it should be al
right. The used shape can be regularly opened from QGIS without any
problems. Opening geotiffs works without problems.
Marco
My PyQGIS test-code:
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
QgsApplication.initQgis()
mapinstance = QgsMapLayerRegistry.instance()
# load shape
shplayer = QgsVectorLayer("/tmp/qgis/foo.shp", "foo", "ogr")
if shplayer.isValid():
print "shplayer succesfully loaded - adding to mapinstance"
mapinstance.addMapLayer(shplayer)
else:
print "shplayer failed to load!"
# load sqlite
sqluri = QgsDataSourceURI()
sqluri.setDatabase('/tmp/qgis/bar.sqlite')
sqluri.setDataSource('', 'bar', 'Geometry')
print sqluri.uri()
sqllayer = QgsVectorLayer(sqluri.uri(), 'bar', 'spatialite')
if sqllayer.isValid():
print "sqllayer succesfully loaded - adding to mapinstance"
mapinstance.addMapLayer(sqllayer)
else:
print "sqllayer failed to load!"
# load tif
tiffileName = "/tmp/qgis/foobar.tif"
tiffileInfo = QFileInfo(tiffileName)
tifbaseName = tiffileInfo.baseName()
tiflayer = QgsRasterLayer(tiffileName, tifbaseName)
if tiflayer.isValid():
print "tiflayer succesfully loaded - adding to mapinstance"
mapinstance.addMapLayer(tiflayer)
else:
print "tiflayer failed to load!"
print mapinstance.mapLayers()
# render map
img = QImage(QSize(800,600), QImage.Format_ARGB32_Premultiplied)
color = QColor(255,255,255)
img.fill(color.rgb())
p = QPainter()
p.begin(img)
p.setRenderHint(QPainter.Antialiasing)
render = QgsMapRenderer()
lst = [ tiflayer.getLayerID(), shplayer.getLayerID(),
sqllayer.getLayerID() ]
render.setLayerSet(lst)
# set extent
rect = QgsRectangle(render.fullExtent())
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('/tmp/qgis/output.png', 'png')
QgsApplication.exitQgis()
Messages are:
Failed to load
shplayer failed to load!
dbname='/tmp/qgis/bar.sqlite' table="bar" (Geometry) sql=
Failed to load
sqllayer failed to load!
tiflayer succesfully loaded - adding to mapinstance
{PyQt4.QtCore.QString(u'foobar20110404130554369'):
<qgis.core.QgsRasterLayer object at 0x92c3b6c>}
More information about the Qgis-developer
mailing list