3

I tried creating a standalone external application of QGIS using python and I followed the tutorial mentioned in the link http://download.osgeo.org/qgis/doc/workshops/foss4g2007_qgis0.9_workshop_en.pdf

After running the python file the viewer opens and allows the user to browse for Shapefiles. The problem is that the Shapefile cannot be viewed in the viewer. It raises an error "Invalid Shapefile" though I added a correct Shapefile everytime I loaded any shapefile.

My code as well as the error is attached. Please tell me where I am wrong.

def addLayer(self):
    file = QFileDialog.getOpenFileName(self, 
               "Open Shapefile", ".", "Shapefiles (*.shp)")
    fileInfo = QFileInfo(file)

    # Add the layer
    layer = QgsVectorLayer(file, fileInfo.fileName(), "ogr")

    if not layer.isValid():
        raise IOError("Invalid Shapefile")

    # Change the color of the layer to gray
    symbols = layer.renderer().symbols()
    symbol = symbols[0]
    symbol.setFillColor(QColor.fromRgb(192, 192, 192))

    # Add layer to the registry
    QgsMapLayerRegistry.instance().addMapLayer(layer)

    # Set extent to the extent of our layer
    self.canvas.setExtent(layer.extent())

    # Set up the map canvas layer set
    c1 = QgsMapCanvasLayer(layer)
    layers = [c1]
    self.canvas.setLayerSet(layers)

And the error window is **enter image description here**

6
  • What is the QGIS prefix that you have specified (if any)? Commented Apr 14, 2015 at 12:12
  • I did set my QGISHOME as c:\Program Files\QGIS Wien. Which is the installation path of QGIS in my windows OS.
    – User123
    Commented Apr 14, 2015 at 12:16
  • I meant your QGIS prefix. You should have a line like this: QgsApplication.setPrefixPath(qgis_prefix, True) before you initialize QGIS. Commented Apr 14, 2015 at 12:23
  • yeah I assigned QGISHOME = C:\Program Files\QGIS Wien and qgis_prefix = os.getenv("QGISHOME")
    – User123
    Commented Apr 14, 2015 at 12:26
  • 1
    Please try with qgis_prefix="C:\\Program Files\\QGIS Wiena\\apps\\qgis" QgsApplication.setPrefixPath(qgis_prefix, True) and let me know. Commented Apr 14, 2015 at 12:32

1 Answer 1

5

Non-valid layers are most of the times due to a wrong QGIS prefix definition.

Please try with:

qgis_prefix="C:\\Program Files\\QGIS Wiena\\apps\\qgis"    
QgsApplication.setPrefixPath(qgis_prefix, True) 

Which should go right before this line:

QgsApplication.initQgis()

Now your tested layers should be valid.

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.