In PyQGIS we can obtain the active (currently selected) layer with

>>> iface.activeLayer()
<QgsRasterLayer: '007' (gdal)>

With a group selected this returns None (?).

QgsInterface does not seem to have a method to obtain the active group, is there any workaround to find out the active group from PyQGIS?


1 Answer 1


The layer tree is a QTreeView object where you can access any selected row via its selectionModel.

def activeGroup():
    tree_view = iface.layerTreeView()
    # retrieve current selected index in the layer tree
    current_index = tree_view.selectionModel().currentIndex()
    # check if index is valid (could be invalid e.g. if layer tree is empty)
    if not current_index.isValid():
    # convert the index to a node object
    node = tree_view.index2node(current_index)
    # check if selected node is a group
    if isinstance(node, QgsLayerTreeGroup):
        return node
# <QgsLayerTreeGroup: test>

The activeGroup function will work equivalent to activeLayer. It returns a QgsLayerTreeGroup object if a group is selected otherwise it returns None.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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