I would like to update one attribute of a feature. However, I don't know to update it using the feature object. I have to use data provider to update it.
layers = QgsMapLayerRegistry.instance().mapLayersByName('my_line')
layer = layers[0]
dp = layer.dataProvider()
it = dp.getFeatures()
for i in range(0, dp.featureCount()):
feat = it.next()
attrs = { 2 : 30 }
layer.dataProvider().changeAttributeValues({ feat.id() : attrs })
Can I change the value of an attribute using QgsFeature
object?
Moreover, is it possible to loop using an iterator object?
Answer
Answering your two questions:
You can change your feature values from the
layer
object, no need to access thedataProvider()
.Yes, you can use the iterator in a
for
loop.
Check the code below:
layers = QgsMapLayerRegistry.instance().mapLayersByName('my_line')
layer = layers[0]
it = layer.getFeatures()
layer.startEditing()
for feat in it:
layer.changeAttributeValue(feat.id(), 2, 30)
layer.commitChanges()
This updates the third (index 2) field value to 30 for all layer features.
Note: As you pointed out, for some reason the QgsFeature object cannot update feature values, although the API says it can.
No comments:
Post a Comment