9

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

1 Answer 1

14

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)
10
  • Thanks so much, bro! It's exactly what I'm looking for. Thanks again Commented Jan 17, 2022 at 9:39
  • another question please, the upper part of the script is to add a new table, but it's added inside the group, how can I edit to add the table outside the group at the top of TOC? because I'm applying other processing scripts to the group and this way it will be applied also to the table, Thanks in advance Commented Jan 17, 2022 at 10:18
  • By default, QGIS places the new layer on top of the selected layer. Commented Jan 17, 2022 at 11:05
  • but inside the group, I want to add it outside to avoid including it in further processing script Commented Jan 17, 2022 at 11:07
  • I've edited the answer. Add the last four lines to your script. Commented Jan 17, 2022 at 11:39

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.