TransWikia.com

Select Group in LayerTree using PyQGIS

Geographic Information Systems Asked by hug117 on May 26, 2021

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?

One Answer

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...

Correct answer by Ben W on May 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP