I am writing a QGIS plugin, which at one point attempts to change several attribute values on a layer. However, in the end no changes are made. If I punch similar code into the built-in Python Console, it works as expected. Code (paraphrased):

grid = self.dlg.gridMapLayerComboBox.currentLayer()
# layer from GUI
prov = grid.dataProvider()

if prov.fieldNameIndex("NewField") == -1:   
    prov.addAttributes( [ QgsField("NewField", QVariant.Int)])
if prov.fieldNameIndex("NewField2") == -1:
    prov.addAttributes( [ QgsField("NewField2", QVariant.Int)])

fldIdx = prov.fieldNameIndex("NewField")
fldIdx2 = prov.fieldNameIndex("NewField2")

for feature in grid.getFeatures():
    ID = feature.id()
    grid.changeAttributeValue(ID, fldIdx, 42)
    grid.changeAttributeValue(ID, fldIdx2, 101)


So there are several similar questions on the site that seem like they should answer my question and I believe I've followed advice in the solutions, but to no avail. There is something I am just not seeing!

How to change the value of an attribute using QgsFeature in PyQGIS? Got Null values when updating attributes with PyQgis

This does not work either:

feature.setAttribute(fldIdx, 42)
  • 2
    I think your problem is grid.updateFeature(feature) try removing that line. I think it's undoing your changes. – Jesse McMillan Jan 13 '16 at 19:12
  • The main problem was I was trying to pass Numpy datatypes and rather than throwing an TypeError, changeAttributeValue just silently failed. – Kris Jan 14 '16 at 14:44
  • My problem was not related to datatypes and removing the line updateFeature(feature) solved the issue (QGIS 2.18.21 32 bits) – nanunga Jun 24 '18 at 17:50

The example code above should work (coincidentally with or without the grid.updateFeature(feature)). The problem was in my actual code I was trying to pass Numpy datatypes and rather than throwing an TypeError, changeAttributeValue() just silently failed.

Always remember to check your variable types when debugging!

  • I think I got the same failure (also without error message) in my code [here] (gis.stackexchange.com/questions/252576/…)? (I'm calculating values as a bumpy array and trying to paste them into the attribute values...) how did you solve your problem? – Nico Aug 19 '17 at 9:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.