4

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()
grid.startEditing()

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

grid.updateFields()
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)
    grid.updateFeature(feature)

grid.commitChanges()

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)
Kris
  • 313
  • 3
  • 12
  • 2
    I think your problem is grid.updateFeature(feature) try removing that line. I think it's undoing your changes. – J M 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

1 Answers1

6

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!

menes
  • 1,421
  • 2
  • 7
  • 24
Kris
  • 313
  • 3
  • 12
  • I think I got the same failure (also without error message) in my code [here] (https://gis.stackexchange.com/questions/252576/adding-new-values-to-existing-attribute-values-in-pyqgis)? (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 09:01