8

To know the active layer and the attribute of the qgis project, I'm using the iface variable in the integrated Python console. But I want to achieve this information through a standalone Python script. So how to retrieve the information (activelayer, attribute, features, etc) without the iface. As per my understanding iface variable will work for the integrated Python console in QGIS.

2
  • 2
    How would you define an active layer without the interface?
    – Dror Bogin
    Dec 1, 2020 at 13:06
  • No need an interface to get active layer in standalone PyQGIS application. Dec 27, 2020 at 22:00

1 Answer 1

10

iface is predefined variable in QGIS. It is defined while QGIS starts and refers to QGIS interface. That means you cannot use iface in your standalone application.

You can use QgsProject.instance() to get the attributes of a project in your application.

project = QgsProject.instance()    

To get the active layer use the script below:

def activeLayer():
    project = QgsProject.instance()

    tree_root = project.instance().layerTreeRoot()
    tree_model = QgsLayerTreeModel(tree_root)
    tree_view = QgsLayerTreeView()
    tree_view.setModel(tree_model)

    return tree_view.currentLayer()


active_layer = activeLayer()

If you would like to use other methods of iface you should similarly define them in your application, like activeLayer above.

2
  • If i use the idea of the script it gives me an error "cannot import name 'QgsLayerTreeView' from 'qgis.core". Any thing I forgot?
    – miraculix
    Mar 29, 2022 at 12:15
  • 1
    @miraculix, very late comment- but QgsLayerTreeView is part of gui library not core. So: from qgis.gui import QgsLayerTreeView
    – Ben W
    Aug 17, 2022 at 7:28

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.