[GIS] Traversing subgroups and group layers with PyQGIS

layertreepyqgisqgis

I am trying to find the name of subgroups using PyQGIS. I have been trying to use Playing with subgroups

I am however unable to traverse and get the names of the subgroup. I have tried the code on this article.

for child in root.children():
  if isinstance(child, QgsLayerTreeGroup):
    print "- group: " + child.name()
    if child.name() == "test": #to check subgroups within test group
        for child in root.children(): #which I think i am making a mistake here because the root is supposed to contain all nodes     

Best Answer

Since you want to start reading children from your main group (not from root anymore), try this (pay attention to the last 3 lines):

for child in root.children():
  if isinstance(child, QgsLayerTreeGroup):
    print "- group: " + child.name()
    if child.name() == "test": #to check subgroups within test group
        for subChild in child.children():
            if isinstance(subChild, QgsLayerTreeGroup):
                subChild.name()