1

I have two groups with unique names, which contain layers using identical names, e.g.:

Group 1

  • Layer A

Group 2

  • Layer A

Is there a smart way to set the active layer to specifically Layer A from e.g. group 2 in PyQGIS?

The layer names should remain identical, as they are automatically generated from a plug-in.

I do know it is possible to set the active layer to the one selected inside QGIS. However, it would be preferable if it was possible to find the layer name within the selected group instead.

7

You can define a method for this.

def select_layer(layer_name, group_name):
    root = QgsProject.instance().layerTreeRoot()
    group = root.findGroup(group_name)
    if group is not None:
        for child in group.children():
            if child.name() == layer_name:
                iface.setActiveLayer(child.layer())
            
select_layer("Layer A", "Group 2")

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