I want to create a standalone application based on QGIS API.
Here is my source code to load a shapefile:
import sys
from qgis.gui import *
from qgis.core import *
from qgis.core import QgsProject
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QWidget
class MapViewer(QMainWindow):
def __init__(self, shapefile):
QMainWindow.__init__(self)
self.setWindowTitle("Map Viewer")
canvas = QgsMapCanvas()
#canvas.useImageToRender(False)
canvas.setCanvasColor(Qt.white)
canvas.show()
layer = QgsVectorLayer(shapefile, "layer1", "ogr")
if not layer.isValid():
raise IOError("Invalid shapefile")
QgsProject.instance().addMapLayer(layer)
QgsProject.instance().mapLayers()
# QgsMapLayerRegistry.instance().addMapLayer(layer)
# canvas.setExtent(layer.extent())
# canvas.setLayerSet(layer)
# canvas.setLayerSet([QgsMapCanvasLayer(layer)])
layout = QVBoxLayout()
layout.addWidget(canvas)
contents = QWidget()
contents.setLayout(layout)
self.setCentralWidget(contents)
# supply path to qgis install location
QgsApplication.setPrefixPath("/usr/bin/qgis", True)
# create a reference to the QgsApplication, setting the
# second argument to False disables the GUI
qgs = QgsApplication([], True)
# load providers
qgs.initQgis()
# Write your code here to load some layers, use processing
# algorithms, etc.
app = QApplication(sys.argv)
viewer = MapViewer("/home/bot/STATE.shp")
viewer.show()
app.exec_()
# When your script is complete, call exitQgis() to remove the
# provider and layer registries from memory
qgs.exitQgis()
I have tried different shapefiles from different location but all of them raise exception of Invalid shapefile.
My PYTHONPATH:
/usr/share/qgis/python
Output:
Traceback (most recent call last): File "./q_test.py", line 57, in
viewer = MapViewer("/home/bot/STATE.shp") File "./q_test.py", line 25, in <strong>init</strong> raise IOError("Invalid shapefile") OSError: Invalid shapefile</p>
shapefilevalue? – Fran Raga Jun 17 '19 at 06:52value? – neferpitou Jun 17 '19 at 06:59/home/bot/STATE.shp– neferpitou Jun 17 '19 at 07:09