[GIS] Problem loading vector layer (pyQGIS)

pyqgispythonqgisUbuntu

I've installed the qgis on ubuntu 12.04 following the instructions on http://hub.qgis.org/projects/quantum-gis/wiki/Download. I am trying to test the Python API and try to do the follwoing

from qgis.core import *
layer = QgsVectorLayer("coast.shp", "coast_shp", "ogr")

But layer.isValid() returns false. Any ideas why it might happen?

Best Answer

I had similar issue.

Found that the problem could be due to the following possibilities:

  1. When you set up the QgsApplication, the PrefixPath must be done correctly.

    My QGIS was installed on /usr/share/qgis.

    But somehow I need to set the PrefixPath as "/usr" & not "/usr/share/qgis":

    QgsApplication.setPrefixPath("/usr", True)
    
  2. The path of the .shp files.

    Assuming they are under a sub-directory from current path, "Maps/", you can load the file with:

    mapFile = "Maps/world_borders.shp"
    layer = QgsVectorLayer(os.path.abspath(mapFileName), mapFileName[mapFileName.rfind("/")+1:-4], "ogr")
    
  3. Lastly, not all .shp files are created 'equal'. ;P

    Some .shp file can be loaded without problem into QGIS & displayed.

    Some, probably created in ESRI ArcMap, require the rest of the files (.shp, .shx, .dbf, .prj, .sbn, .sbx)

Hope this info help.

Related Question