2

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     
  • Hi @kartoza-geek, can you elaborate on the output of the above script and at which stage it fails? – Matthias Kuhn Sep 7 '15 at 17:55
  • The script runs well but does not give expected results. If I have a group layer called test and subgroups called test 1 and test 2 they are not printed – kartoza-geek Sep 7 '15 at 18:55
  • 1
    Try for subChild in child.children(): and then print subChild.name(), since you want to start reading children from your main group (not from root anymore). – Germán Carrillo Sep 7 '15 at 19:20
  • for some reason it does not work. It throws an error QgsLayerTreeLayer' object has no attribute 'name. – kartoza-geek Sep 8 '15 at 7:06
  • 1
    I'll post it as an answer, so that we can mark this question as answered. – Germán Carrillo Sep 8 '15 at 14:04
2

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()
  • yes, it worked. That's the code I ended up using. thanks for the help – kartoza-geek Sep 8 '15 at 14:20

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.