3

Following code updates the value of field ("name") in console and shows the result but actual attribute table does not get update .Can anybody suggest the error in code.

layer=iface.activeLayer()

selected_feature=layer.selectedFeatures()

layer.startEditing()

for feature in selected_feature:

    feature["name"]="Test name"

layer.commitChanges()
4

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 commiting 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)
5
  • @BipinThapaliya - Most welcome, glad it helped :)
    – Joseph
    Mar 29 '19 at 11:20
  • 1
    Not working for me .Tried both of these versions. I am exhausted ;( Aug 1 '19 at 12:41
  • @ChetanVashisth - Post a question with what you tried and hopefully people will respond :)
    – Joseph
    Aug 1 '19 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.. :) Aug 1 '19 at 12:45
  • I'm getting a NameError 'edit' is not defined... Jul 22 '20 at 13:42
0

QgsProject.instance().reloadAllLayers() worked for me on QGIS 3.10.

2
  • Worked for me on QGIS 3.10 Apr 9 at 13:20
  • 1
    Welcome to GIS SE! As a new user please take the tour. A good answer should include details about how to use your suggestion and info about what it does. Please edit your answer to add additional info.
    – Midavalo
    Apr 9 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.