5

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.

1 Answer 1

6

You have to enable editing on the layer:

layer.startEditing()

and update each feature after changing its attribute:

layer.updateFeature(feature)
3
  • Thanks a lot. so I figured that I also had to add "layer.updateFeature(feature)" and "layer.commitChanges()". Just one question: it takes a long time to execute "layer.updateFeature(feature)". any idea on how to do it faster, or once at the very end for all the features?
    – Alex
    Commented Mar 14, 2014 at 21:54
  • Also, I don't know the rules that well; may I edit your answer to add the other two lines?
    – Alex
    Commented Mar 14, 2014 at 22:07
  • Yes you can edit.
    – Nathan W
    Commented Mar 14, 2014 at 22:28

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.