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[:]
    for i, group in enumerate(rev):

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.

  • This QA gis.stackexchange.com/questions/198296/… might get you going in the right direction. – TomazicM Apr 22 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 Apr 22 at 22:16

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':
  • 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 Apr 23 at 13:56
  • @CNIDog - Glad it helped :) – Joseph Apr 24 at 12:33

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.