Removing all layers from group using PyQGIS?
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)
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)
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