Sunday 18 November 2018

qgis - How to update the attribute table of feature using PyQGIS?


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

Answer



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)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...