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!
This does not work either: