2

I try to test a PyQGIS standalone script which should just show one Shapefile. Sounds pretty simple but does not work.

Here is my script:

from PyQt4 import *
from PyQt4 import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
import sys
import os

qgishome = "C:\OSGeo4W64\apps\qgis"

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

canvas = QgsMapCanvas()
canvas.setCanvasColor(Qt.yellow)
canvas.enableAntiAliasing(True)
canvas.show()

layer = QgsVectorLayer(r"C:/daten/polygons.shp", "Testdaten", "ogr")
reg = QgsMapLayerRegistry.instance()
reg.addMapLayer(layer)
canvas.setExtent(layer.extent())
canvas.setLayerSet([QgsMapCanvasLayer(layer)])
QgsApplication.exitQgis()

app.exec_()

app.exitQgis()

The Window openes, I can see the yellow background but the Layer is not shown. instad of that there is an error message:

QGraphicsScene::addItem: item has already been added to this scene
QObject::connect: Cannot connect (null)::repaintRequested() to QgsMapCanvas::ref
resh()
QObject::connect: Cannot connect (null)::layerCrsChanged() to QgsMapCanvas::laye
rCrsChange()

Sometimes this also brings python to crash, so that a windows error reporting is opened.

I loaded the neccessary environmental variables, which should be ok, as I can import qgis.core and qgis.gui without problems.

does anyone has an idea what's the problem?

2

You are on the right track.

The thing that bit you are the backslashes in your prefix path \ which are escape sequences in python. Just do it the same way as you do it with the layer path and use slashes / instead.

qgishome = "C:/OSGeo4W64/apps/qgis"

A useful snippet that you can run after QgsApplication.initQgis() that makes sure that the providers are loaded correctly is the following one, found here.

if len(QgsProviderRegistry.instance().providerList()) == 0:
    raise RuntimeError('No data providers available.')

or check layer.isValid() to see if the layer was really loaded correctly.

Another thing that you probably don't want to do is to call QgsApplication.exitQgis() before app.exec_()

And finally concerning the warnings, they are unrelated to your code and don't hurt at all. And I think they should be gone with the most recent release.

  • Thanks for your answer! It works great. Unfortunally there happened something weired to my useraccount here. My question isn't assignet to my account anymore, so I cannot mark it as answered or upvote the answer ;( – Schlockspecht Jun 29 '15 at 19:23

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.