I'm trying to create and update a field and ,for now, just change it's value to 2.
Here is my code:
layer = qgis.utils.iface.activeLayer()
index = layer.fieldNameIndex("P")
# if index == -1: # field doesn't exist
caps = layer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.AddAttributes:
res = layer.dataProvider().addAttributes( [ QgsField("P", \
QVariant.Double) ] )
layer.updateFields()
for feature in layer.getFeatures():
# None of these work
index = layer.fieldNameIndex("P")
feature["P"] = 2
feature.setAttribute(index,(2.0))
feature.attributes()[index] = 2
#################
layer.commitChanges()
But all I get is a new column filled with NULL values. I can't figure out where I'm making a mistake though.
EDIT:
It seems the actual value has been updated (last value) :
feature.attributes()
[28965.0, 209294.0, 43.0, 207459.0, NULL, u'HANOVER', u'AV', 3901.0, 4049.0, 3900.0, 4048.0, u'Hanover Av', u'LOCAL STR', NULL, NULL, u'LOCAL STREET', NULL, 0.0, 50.0, 50.0, 5436.0, 43.0, 25.0, 209294.0, NULL, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, NULL, 0.0, 0.0, 0.0, 0.0, 1, 2]
But in the shapefile, it still shows NULL.
Answer
You have to enable editing on the layer:
layer.startEditing()
and update each feature after changing its attribute:
layer.updateFeature(feature)
No comments:
Post a Comment