10

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.

0

3 Answers 3

11

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

I have this function to remove a group and all his layers. I think is nearly what you want.

def removeGroup(name):
    root = QgsProject.instance().layerTreeRoot()
    group = root.findGroup(name)
    if not group is None:
        for child in group.children():
            dump = child.dump()
            id = dump.split("=")[-1].strip()
            QgsMapLayerRegistry.instance().removeMapLayer(id)
        root.removeChildNode(group)

You could use it like this:

removeGroup("groupname")

If you dont want to remove the group, just his child layers, then remove this line:

root.removeChildNode(group)
0
4

Update for QGIS 3.

Based in @cag answer only need change this line :

QgsMapLayerRegistry.instance().removeMapLayer(id)

to

QgsProject.instance().removeMapLayer(id)

And work like a charm

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.