Skip to main content
1 of 4
Kalak
  • 4k
  • 12
  • 28

You need to either use only the .dataProvider() (QgsVectorDataProvider) methods which call the underlying data and modify it or use the edit methods of QgsVectorLayer.

so, either :

layer = iface.activeLayer()
layer.startEditing()
all_features = layer.getFeatures()
for feat in all_features:
    geom = feat.geometry()
    x = geom.asPoint().x()
    y = geom.asPoint().y()
    
    feat.setAttribute('x', x)
    feat.setAttribute('x', x)
    
    layer.updateFeature(feat)
 
# Commit changes
layer.commitChanges()

or

layer = iface.activeLayer()
all_features = layer.getFeatures()
for feat in all_features:
    geom = feat.geometry()
    x = geom.asPoint().x()
    y = geom.asPoint().y()
    
    new_x = {feat.fieldNameIndex('x'): x}
    layer.dataProvider().changeAttributeValues({feat.id(): new_x })
    
    new_y = {feat.fieldNameIndex('y'): y}
    layer.dataProvider().changeAttributeValues({feat.id(): new_y })
Kalak
  • 4k
  • 12
  • 28