3

I am trying to change the values of an attribute in one of my layers. My code is as follows:

from qgis.utils import iface
from PyQt4.QtCore import *
layer =iface.activeLayer()
pr=layer.dataProvider()
layer.startEditing()
for f in layer.getFeatures():
    geom=f.geometry()
    xval= geom.asPoint().x()
    f['XX']=xval
    layer.commitChanges()
    print f['XX']
for f in layer.getFeatures():
    print f['XX']

For my first print statement, I am getting the values out that I want, but when I run the second print statement, the values are what they were before running the code.

Am I Not committing changes correctly?

1 Answer 1

2

You can't directly edit a feature returned by getFeatures() - those are copies of the underlying layer features, so any changes you make won't actually affect the layer itself. What you need to do is use the QgsVectorLayer.changeAttributeValues method here. So something like:

xx_field_index = 0 # or whatever the index is for the field you want to change
layer.startEditing()
for f in layer.getFeatures():
    geom=f.geometry()
    xval=geom.asPoint().x()
    layer.changeAttributeValue(f.id(), xx_field_index, xval)

layer.commitChanges()
4
  • Hmm, still can't get it to work. Is there anything else that I should look into? I am very new to QGIS, so I may just be unfamiliar with the basics. f.id() prints the row number, xx_field_index is the column number of the attribute (constant), and xval is correct coordinate value I want. However, the layer.changeAttributeValue( ) function doesn't seem to work
    – efrank
    Commented May 30, 2018 at 13:21
  • Which qgis version are you using?
    – ndawson
    Commented May 30, 2018 at 18:35
  • I am using 2.18.20
    – efrank
    Commented May 30, 2018 at 19:09
  • So I tried your code with a different attribute, and it worked! So I think there was just something wrong with my attribute when I created it that prevented it from changing. Thanks for your help
    – efrank
    Commented May 30, 2018 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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