14

I try to set feature attributes by attribute name with this code

pr = layer.dataProvider()
pr.addAttributes([QgsField("test", QVariant.Int)])
layer.updateFields()
for feature in layer.getFeatures():
 attrName = 'test'
 feature[attrName] = 1

but in result I have NULL in all fields. If I use

feature.setAttributes([1])

it works properly.

What I do wrong? Why feature[attrName] = 1 doesn't work?

Update: Find this solution

pr = layer.dataProvider()
pr.addAttributes([QgsField("test", QVariant.Int)])
layer.updateFields()
for feature in layer.getFeatures():
 attrName = 'test'
 feature[attrName] = 1
 pr.changeAttributeValues({feature.id() : {pr.fieldNameMap()[attrName] : 1}})

2 Answers 2

24

QGIS can use field names and indexes:

feature['fieldname'] = 10
feature[1] = 10

Make sure you are in edit mode before you do anything on the layer:

layer.startEditing()
feature['fieldname'] = 10
layer.updateFeature(feature)

#Call commit to save the changes
layer.commitChanges()
0
-1

AFAIK, QGIS uses field indexes, not field names, for assignment. Try using feature[layer.fieldNameIndex(attrName)] = 1.

4
  • I try: feature.setAttribute(attrName, 1) and feature.setAttribute(layer.fieldNameIndex(attrName), 1) with same results (api reference have two setAttribute methods for feature with index and name) Commented Jan 20, 2014 at 21:38
  • feature[layer.fieldNameIndex(attrName)] = 1 also the same. Commented Jan 20, 2014 at 21:44
  • Have you initialised the attributes (feature.initAttributes(len(attributes)))? Commented Jan 20, 2014 at 21:45
  • Add feature.initAttributes(1) with same result. But check feature[attrName] and got 1 which I looking for. But still have NULL if I open Attribute Table in gui. Commented Jan 20, 2014 at 21:56

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.