TransWikia.com

How to update the attribute table of feature using PyQGIS?

Geographic Information Systems Asked by Bipin Thapaliya on June 22, 2021

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

2 Answers

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)

Correct answer by Joseph on June 22, 2021

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

Answered by Romário Carvalho Neto on June 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP