4

I'd like to open a shapefile in a standalone PyQGis App. The App starts and runs without a problem but a get an false-Return in the isValid()-Function on the Layer and the Layer doesn't show up.

I tried this on two different shapefiles and did make sure that the filepath is correct.

Can anyone tell me is there is something wrong or missing in the code or how I can debug this problem any further?

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

app = QtGui.QApplication(sys.argv)

window = QtGui.QMainWindow()
window.setGeometry(550, 550, 500, 300)
window.setWindowTitle("Test Window")

window_frame = QtGui.QFrame(window)
window.setCentralWidget(window_frame)
frame_layout = QtGui.QGridLayout(window_frame)

canvas = QgsMapCanvas()
frame_layout.addWidget(canvas)

filepath = "/home/stefan/testlayer/test.shp"

layer = QgsVectorLayer(filepath, "testlayer", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(layer)
if not layer.isValid():
    print "Layer not valid"
canvas_layer = QgsMapCanvasLayer(layer)
canvas.setLayerSet([canvas_layer])
canvas.zoomToFullExtent()

window.show()

sys.exit(app.exec_())
3
  • Does the shapefile work in other applications (QGIS) without issue? Commented Oct 2, 2016 at 16:13
  • Yes, both show up in Qgis without any problems. Forgot to write that. ;) Commented Oct 2, 2016 at 16:40
  • Did you try to load and check the validity of the layer in the qgis console?
    – Matte
    Commented Oct 2, 2016 at 17:27

1 Answer 1

2

You need to adjust a couple of things:

  1. Adjust your imports according to Why the order of imports matters in a standalone PyQGIS processing script?:

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

    NOTE: I'm not a big fan of importing everything (using the *). Since your script uses a few classes, you could import only them. That's optional, but better.

  2. Add the following 2 lines (right below app = QtGui.QApplication(sys.argv)) to initialize the QGIS application, which registers providers and the reference system database, among other things QGIS needs, even for standalone applications, see Failed to create memory layers in QGIS application on Linux for details:

    QgsApplication.setPrefixPath("/usr", True)
    QgsApplication.initQgis()
    

That's it. Now you should get your layer loaded into the standalone application.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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