Saturday 22 July 2017

qgis - PyQGIS: Change attribute value doesn't work, results in NULL


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)

Answer



The example code above should work (coincidently 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!


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...