pyqgis – How to Retrieve the Active Group in PyQGIS

layertreepyqgis

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?

Best Answer

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():
        return
    # 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
    
    
print(activeGroup())
# <QgsLayerTreeGroup: test>

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

Related Question