Friday 26 July 2019

qgis - Viewer not displaying the data in my standalone PyQGIS Application


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**



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...