3

I'm following the following instructions on getting Python to work with QGIS, outside the QGIS GUI itself: Using PyQGIS in custom applications.

But for some reason the GUI is not appearing, yet the layer seems to be loading fine and it also returns the correct feature count. What am I doing wrong?

from qgis.core import *

qgs = QgsApplication([], True)

qgs.initQgis()

vlayer = QgsVectorLayer("test.gpkg")
if not vlayer.isValid():
    raise Exception("Layer failed to load!")


project = QgsProject.instance()
project.addMapLayer(vlayer)

print(vlayer.featureCount());

# Write your code here to load some layers, use processing
# algorithms, etc.

qgs.exitQgis()
1
  • 1
    You create a Qt / PyQGIS main loop and run some code in it. Have you instantiate widgets and show them ? my_widget = QgsColorDialog(); my_widget.show() ? Jan 17, 2022 at 14:45

1 Answer 1

6

Any GUI doesn't appear when using PyQGIS standalone application. You have to construct it.

Here is an example:

from qgis.core import *
from qgis.gui import *
from qgis.PyQt.QtWidgets import *

### GUI Construction ###
class MapViewer(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self, None)

        self._canvas = QgsMapCanvas()
        self._root = QgsProject.instance().layerTreeRoot()

        self.bridge = QgsLayerTreeMapCanvasBridge(self._root, self._canvas)
        self.model = QgsLayerTreeModel(self._root)
        self.model.setFlag(QgsLayerTreeModel.ShowLegend)
        self.layer_treeview = QgsLayerTreeView()
        self.layer_treeview.setModel(self.model)

        self.layer_tree_dock = QDockWidget("Layers")
        self.layer_tree_dock.setObjectName("layers")
        self.layer_tree_dock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        self.layer_tree_dock.setWidget(self.layer_treeview)

        self.splitter = QSplitter()
        self.splitter.addWidget(self.layer_tree_dock)
        self.splitter.addWidget(self._canvas)
        self.splitter.setCollapsible(0, False)
        self.splitter.setStretchFactor(1, 1)

        self.layout = QHBoxLayout()
        self.layout.addWidget(self.splitter)
        self.contents = QWidget()
        self.contents.setLayout(self.layout)
        self.setCentralWidget(self.contents)

        self.load_layers()

    def load_layers(self):
        # Adding a sample layer
        layer = QgsVectorLayer("test.gpkg", 'Layer1', 'ogr') # CHANGE PATH
        QgsProject.instance().addMapLayer(layer)
        self._canvas.setExtent(layer.extent())
        self._canvas.setLayers([layer])
########################
        
qgs = QgsApplication([], True)
qgs.initQgis()

### Call the GUI built by you ###
main_window = MapViewer()
main_window.show()

qgs.exec_()
qgs.exitQgis()

enter image description here

6
  • Got it; it wasn't entirely clear from the instructions here: docs.qgis.org/3.16/en/docs/pyqgis_developer_cookbook/… that I needed to construct the GUI myself. Now it is :) Thanks!
    – Mar Tijn
    Jan 17, 2022 at 21:58
  • What is this flag? self.model.setFlag(0x25043) Mar 14 at 8:18
  • @bugmenot123 I really don't remember why I used it. Mar 14 at 11:00
  • @bugmenot123 I probably tried something and forgot to remove. Mar 14 at 11:12
  • I'll try to decipher the bitmask tomorrow, should be fairly easy. Thanks for this great example BTW! OK if I try to add it to the official docs? Mar 14 at 16:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.