3

I create a script in order to make specific events according to the layers. I have already performed a sort according to the name of the layers. This is how I did it:

keep_layer = ['layer1', 'layer2']
for lay in QgsProject.instance().mapLayers().values():
       for k_layer in keep_layer :
           if lay.name() == k_layer :
               #Do something
           else:
               pass

This sorting allows me to make precise modifications on the layers with the same name as those entered in the keep_layer variable.

I also created a variable keep_group which will have the groups for which I want to make changes. Here is the type of subgroup I'm trying to select (screenshot) :

The sub-groups in question are framed in red

I thought of something like the previous sort but I can't select the name of the subgroups.

keep_group = ['group1', 'group2', 'group3']
for lay in QgsProject.instance().mapLayers().values():
        for k_group in keep_group :
            if lay.name() == k_group :
                for children in k_goup.children():
                    #Do something
            else:
                pass

How to select a subgroup according to its name in the LayerTree?

3

You can do it simply like this:

group_names = ['group1', 'group2', 'group3']

root = QgsProject.instance().layerTreeRoot()
for group in root.findGroups():
    if group.name() in group_names:
        #Do something...
2
  • 1
    Perfect, that's exactly what I needed! Thank you! I didn't know about the existence of the findGroups() method before
    – hug117
    May 25 '21 at 10:38
  • 1
    You are most welcome! Glad it's what you were looking for.
    – Ben W
    May 25 '21 at 10:55

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.