I have 3 groups of layers, layer names are the same in the 3 groups as shown in this image below:
I want to make a table of 4 fields:
- layer names of group (1),
- layer lengths of group (1),
- Feature count of group (2),
- Feature count of group (3),
I am trying with this code:
#Create an empty table in memory and add fields
newtable = QgsVectorLayer("None", "Layer Length", "memory")
provider = newtable.dataProvider()
provider.addAttributes([QgsField('Layer Name', QVariant.String),
QgsField('Length', QVariant.Double),\
QgsField('Rl Count', QVariant.Double),\
QgsField('SL Count', QVariant.Double)])
newtable.updateFields()
group_names = ['group1', 'group2']
for name in group_names:
group = root.findGroup(name)
layers = [layer.layer() for layer in group.children()]
for lyr in layers:
total_length = sum([r.geometry().length() for r in lyr.getFeatures()])
f = QgsFeature()
f.setAttributes([lyr.name(), total_length])
provider.addFeatures([f])
group_names = ['RL', 'SL']
for name in group_names:
group = root.findGroup(name)
layers = [layer.layer() for layer in group.children()]
for lyr in layers:
Featurecount = lyr.featureCount()
f = QgsFeature()
f.setAttributes([lyr.name(), Featurecount])
provider.addFeature(f)
QgsProject.instance().addMapLayer(newtable)
the code gives me the following table, How can I edit the code to assign the feature count numbers to the layer having the same name? as here in this image:
Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
asked Jan 24, 2022 at 8:12
1 Answer 1
I assume all layers in the groups have the same order
root = QgsProject.instance().layerTreeRoot()
#Create an empty table in memory and add fields
newtable = QgsVectorLayer("None", "Layer Length", "memory")
provider = newtable.dataProvider()
provider.addAttributes([QgsField('Layer Name', QVariant.String),
QgsField('Length', QVariant.Double),
QgsField('RL Count', QVariant.Double),
QgsField('SL Count', QVariant.Double)])
newtable.updateFields()
group = root.findGroup("group1")
rl = root.findGroup("RL")
sl = root.findGroup("SL")
stack = [group.children(), rl.children(), sl.children()]
for glyr, rlyr, slyr in zip(*stack):
total_length = sum([r.geometry().length() for r in glyr.layer().getFeatures()])
rl_count = rlyr.layer().featureCount()
sl_count = slyr.layer().featureCount()
f = QgsFeature()
f.setAttributes([glyr.name(), total_length, rl_count, sl_count])
provider.addFeatures([f])
QgsProject.instance().addMapLayer(newtable, False)
root.insertLayer(0, newtable)
answered Jan 25, 2022 at 22:46
-
It's exactly what I'm looking for, It will help me a lot, I'm thankful for you, bro!Ahmed Kamel– Ahmed Kamel2022年01月26日 08:59:19 +00:00Commented Jan 26, 2022 at 8:59
lang-py