3

According to this thread on using the iface module in a standalone pyQGIS script it is not possible to use the iface module in a standalone script, only being accessible within a QGIS Plugin.

In the official QGIS documentation for the QgisInterface module it states that it is accessible only via QGIS Plugins and not standalone scripts

My question is how I could access the map canvas and the manually set extent of a QGIS project using the pyQGIS module or set the active layers in a given QGIS project as most of the examples use the qgis.utils.iface.setactivelayer() function hasn't worked for me up until now

1 Answer 1

4

For the map canvas, you need to reuse the code from https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/canvas.html#embedding-map-canvas in your standalone application to create your own canvas and sync it with the layers from your QgsProject instance in your script. With your newly canvas, you will be able to get the reference to the canvas and set your extent.

You may try using the following logic (combined from these two other answers PYQGIS signal for layer tree when active layer changed & Getting Layer Properties of QGIS on standalone application using PyQGIS API) for the active layer part. It does not depend of iface and you can get the "active layer" (PS: tested inside QGIS not in the standalone app but could help you solve your issue as no iface anywhere)

# Create your standalone TreeView, no iface deps

# Layer Tree View
layerTreeRoot = QgsProject.instance().layerTreeRoot()
layerTreeModel = QgsLayerTreeModel(layerTreeRoot)
layerTreeView = QgsLayerTreeView()
layerTreeView.setModel(layerTreeModel)

layoutWidgetLayout = QHBoxLayout()
layoutWidgetLayout.addWidget(layerTreeView)
layerWidget = QWidget()
layerWidget.setLayout(layoutWidgetLayout)

# Set the logic to listen to active layer

def test(lyr):
    print(lyr.id())

layerTreeView.currentLayerChanged.connect(test)

# Then show the component
layerWidget.show()

# If you click on the layer, it will return the layer id
# If you rather want to set manually the active layer, use the method
# layerTreeView.setCurrentLayer(your_layer) # See https://qgis.org/api/classQgsLayerTreeView.html
2
  • Hello Thomas, thank you so much for the response on the question. I am wondering what you mean by getting the layers reference rather that printing the id of the active layer when listening for the active layer
    – Nur-Hassan
    Commented May 19, 2020 at 23:15
  • Sorry, remove the comment as it was misleading
    – ThomasG77
    Commented May 20, 2020 at 1:22

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.