[GIS] Removing all layers from group using PyQGIS

group-layerlayerspyqgis

I want to remove all layers from a distinct group.

root = QgsProject.instance().layerTreeRoot()
the_group = root.findGroup("my_group")

parentGroup = the_group.parent()

I think I have to loop the elements of the group and remove them

for i in parentGroup.children():
...

And then calling the removeMapLayer() method within the loop.

But I can't put these things together.

Best Answer

dump() method of QgsLayerTreeLayer should be only used for debug purpose. You can do it much nicer this way:

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup(groupName)

if group is not None:
    for child in group.children():
        if isinstance(child, QgsLayerTreeLayer):
            QgsProject.instance().removeMapLayer(child.layerId())

The code above will remove all layers that are immediately inside the group. If the group has subgroups inside and they also have layers, they won't be removed.


If you want to remove the whole group instead (with layers and groups inside), just call:

root = QgsProject.instance().layerTreeRoot()
group = root.findGroup(groupName)
if group is not None:
    root.removeChildNode(group)
Related Question