3

I am updating a plugin from QGIS 2 to 3. I need to iterate through the groups (the names are dynamic) and remove them with their respective child layers. I need to get a list of groups and then iterate through the groups and delete them. The original code is as follows:

legend = self.iface.legendInterface()
group_names = legend.groups()
rev = self.groups[:]
rev.reverse()
...
    for i, group in enumerate(rev):
        legend.removeGroup(group)

I replaced self.iface.legendInterface() with QgsProject.instance().layerTreeRoot() but group_names = legend.groups() fails with the message 'QgsLayerTree' object has no attribute 'groups'

What is the proper container of the groups and how do I access the collection; and, once found, how do I delete those groups? A search for information on how to remove groups from a layer tree in QGIS 3 has proven fruitless.

2
  • This QA gis.stackexchange.com/questions/198296/… might get you going in the right direction.
    – TomazicM
    Commented Apr 22, 2019 at 18:54
  • Unfortunately, the referenced link is of little help. For one, I cannot perform a findGroup() by group name because I do not know the name(s). There may be several, so I will need to iterate through them by index, not by name. Additionally, I need to delete the group, not just the layers in it.
    – CNIDog
    Commented Apr 22, 2019 at 22:16

1 Answer 1

5

You could delete groups by removing their nodes from the QgsProject::layerTreeRoot().

The following example iterates through the groups and removes a group and all of its layers if the name matches:

root = QgsProject.instance().layerTreeRoot()

for group in [child for child in root.children() if child.nodeType() == 0]:
    if group.name() == 'group1':
        root.removeChildNode(group)
2
  • 1
    Since group the names may be dynamically generated, I will never know all the names, but I can simply remove the if and iterate through them all and delete them all (which is the aim of the algorithm). Upvoted!
    – CNIDog
    Commented Apr 23, 2019 at 13:56
  • @CNIDog - Glad it helped :)
    – Joseph
    Commented Apr 24, 2019 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.