Monday, 7 May 2018

qgis - How to change the value of an attribute using QgsFeature in PyQGIS?


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:




  1. You can change your feature values from the layer object, no need to access the dataProvider().




  2. 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

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...