7

I have a project which has dozens of groups and subgroups. E.g.:

Main_Group > Sub_Group_1 > Sub_Group_1A > Layer_1A
                                        > Layer_2A

How can I access those layers which are contained within Sub_Group_1A?

I currently have this:

root = QgsProject.instance().layerTreeRoot()
for child in root.children():
  if isinstance(child, QgsLayerTreeGroup):
    if child.name() == "Main_Group":
        for subChild in child.children():
            if isinstance(subChild, QgsLayerTreeGroup):
                if subChild.name() == 'Sub_Group_1':
                    # What next?

I have read through the following sources and can get layers in Sub_Group_1 but not in Sub_Group_1A:

Joseph
  • 75,746
  • 7
  • 171
  • 282

3 Answers3

4

There is a handy option in the QgsLayerTreeGroup class that you can use: findGroup. It traverses the whole tree. So, in your case, this would be enough:

root = QgsProject.instance().layerTreeRoot()
subGroup1A = root.findGroup('Sub_Group_1A')
for child in subGroup1A.children():
    if isinstance(child, QgsLayerTreeLayer):
        child.layerName()
Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
0

Eugh, I guess one method is to:

  1. Search the children of Main_group, then
  2. Search the children of Sub_Group_1 and then
  3. Search the children of Sub_Group_1A.

Basically repeating the loops, I'm hoping there is a much nicer and efficient way of accessing those layers but for now, here's the code I used:

root = QgsProject.instance().layerTreeRoot()
for child in root.children():
    if isinstance(child, QgsLayerTreeGroup):
        if child.name() == "Main_Group":
            for subChild in child.children():
                if isinstance(subChild, QgsLayerTreeGroup):
                    if subChild.name() == 'Sub_Group_1':
                        if isinstance(subChild, QgsLayerTreeGroup):
                            for sub_subChild in subChild.children():
                                if isinstance(sub_subChild, QgsLayerTreeGroup):
                                    if sub_subChild.name() == 'Sub_Group_1A':
                                        for layers in sub_subChild.children():
                                            print layers.layerName()
Joseph
  • 75,746
  • 7
  • 171
  • 282
0

For x number of subgroups you can use that script:

def getLayersOfGroup(group):
    """That function find all layers under given group"""
    for child in group.children():
        if isinstance(child, QgsLayerTreeLayer):
            print(child.layer().name()
        elif isinstance(child, QgsLayerTreeGroup):
            getLayersOfGroup(child)
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup("GROUP NAME")
if group:
    getLayersOfGroup(group)
Mustafa Uçar
  • 1,581
  • 18
  • 29