PyQGIS Layers – How to Select Layers in a Group

layerspyqgis

This script is applied to all layers on the TOC, and I want to improve it to apply only to layers of a specific group

# Create an empty table in memory and add fields
newtable = QgsVectorLayer("None", "Results", "memory")
provider = newtable.dataProvider()
provider.addAttributes([QgsField('Layername', QVariant.String),
                        QgsField('Length', QVariant.Double)])
newtable.updateFields()

# For each table added to the map calculate length and 
# add layername and length to the created table
for lyr in QgsProject.instance().mapLayers().values():
    f = QgsFeature()
    total_length = sum([r.geometry().length() for r in lyr.getFeatures()]) #Possible to round decimals here
    f.setAttributes([lyr.name(), total_length])
    provider.addFeature(f)
    
QgsProject.instance().addMapLayer(newtable)

Best Answer

You can use the following lines:

newtable = QgsVectorLayer("None", "Results", "memory")
provider = newtable.dataProvider()
provider.addAttributes([QgsField('Layername', QVariant.String),
                        QgsField('Length', QVariant.Double)])
newtable.updateFields()

# find group
group_name = "group2" # specify group name
root = QgsProject.instance().layerTreeRoot()
group = root.findGroup(group_name)

# layer list in the group
layers_in_group = [layer.layer() for layer in group.children()]

for lyr in layers_in_group:
    total_length = sum([r.geometry().length() for r in lyr.getFeatures()])
    
    f = QgsFeature()
    f.setAttributes([lyr.name(), total_length])
    provider.addFeatures([f])

QgsProject.instance().addMapLayer(newtable, False)

root.insertLayer(0, newtable)