The following code updates the value of the field ("name"
) in the console and shows the result but the actual attribute table does not get updated. Can anybody suggest the error in the code?
layer = iface.activeLayer()
selected_feature = layer.selectedFeatures()
layer.startEditing()
for feature in selected_feature:
feature["name"] = "Test name"
layer.commitChanges()
2 Answers 2
You need to update the layer with the new feature values using:
layer.updateFeature(feature)
So it should look something like:
layer = iface.activeLayer()
selected_feature = layer.selectedFeatures()
layer.startEditing()
for feature in selected_feature:
feature["name"] = "Test name"
layer.updateFeature(feature)
layer.commitChanges()
Or shorten it slightly by editing and committing the changes in one go using with edit()
:
layer = iface.activeLayer()
selected_feature = layer.selectedFeatures()
with edit(layer):
for feature in selected_feature:
feature["name"] = "Test name"
layer.updateFeature(feature)
-
@BipinThapaliya - Most welcome, glad it helped :)Joseph– Joseph2019年03月29日 11:20:46 +00:00Commented Mar 29, 2019 at 11:20
-
1Not working for me .Tried both of these versions. I am exhausted ;(Chetan Vashisth– Chetan Vashisth2019年08月01日 12:41:33 +00:00Commented Aug 1, 2019 at 12:41
-
@ChetanVashisth - Post a question with what you tried and hopefully people will respond :)Joseph– Joseph2019年08月01日 12:43:24 +00:00Commented Aug 1, 2019 at 12:43
-
I have just tried your code above and its not working and i just want to update a field in the attribute table. So i thought i do not have to ask a question for that.. :)Chetan Vashisth– Chetan Vashisth2019年08月01日 12:45:37 +00:00Commented Aug 1, 2019 at 12:45
-
I'm getting a NameError 'edit' is not defined...Jochen Schwarze– Jochen Schwarze2020年07月22日 13:42:39 +00:00Commented Jul 22, 2020 at 13:42
QgsProject.instance().reloadAllLayers()
worked for me on QGIS 3.10.
-
Worked for me on QGIS 3.10Romário Carvalho Neto– Romário Carvalho Neto2021年04月09日 13:20:30 +00:00Commented Apr 9, 2021 at 13:20
-
1
Explore related questions
See similar questions with these tags.