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)
frame_layout = QtGui.QGridLayout(window_frame)

canvas = QgsMapCanvas()

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

layer = QgsVectorLayer(filepath, "testlayer", "ogr")
if not layer.isValid():
    print "Layer not valid"
canvas_layer = QgsMapCanvasLayer(layer)


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

1 Answer 1


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)

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


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.