6

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.

7

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():
        QgsMapLayerRegistry.instance().removeMapLayer(child.layerId())
    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)
3

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, privacy policy and cookie policy

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