8

I'm trying to modify the values of some selected features. I have written this small script, but nothing happens when I run it. Is there something that I've missed? Here is my code.

lyr = qgis.utils.iface.activeLayer()
features = lyr.selectedFeatures()

lyr.startEditing()
lyr.updateFields()
for f in features:
    fid= f.id()
    lyr.changeAttributeValue(fid,12,"0")
    lyr.updateFeature(f)

print "elemento alterado"

lyr.commitChanges()

1 Answer 1

5

Just remove the lyr.updateFeature(f) line that is inside your for loop. You don't need it and, according to the docs, it's also inefficient.

If that doesn't work, make sure the 13th field is of type String.

2
  • My guess about what's happening: lyr.changeAttributeValue(fid,12,"0") updates the value, but the object in f remains unchanged. So lyr.updateFeature(f) reverts it back to the original value. Is that right?
    – jpmc26
    Commented Jan 7, 2016 at 19:57
  • To be honest, I don't understand how updateFeature does its job. I just identified a method that works modifying feature attributes (according to the API, there are several ways) and use it every time. I haven't needed updateFeature at all. Perhaps a QGIS core dev could help us here. Commented Jan 7, 2016 at 21:12

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.