5

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

Taras
  • 32,823
  • 4
  • 66
  • 137

2 Answers2

9

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)

Taras
  • 32,823
  • 4
  • 66
  • 137
Joseph
  • 75,746
  • 7
  • 171
  • 282
-1

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

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389