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)
0

2 Answers 2

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!

0
0

Insted of using .commitChanges(), you can use .commitErrors() which will return the status of the changes and could give more control over the error handling.
There's more info over the documentation and other userfull methods.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.