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}})
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jan 20, 2014 at 21:25

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()
answered Jan 20, 2014 at 22:44
0
-1

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

answered Jan 20, 2014 at 21:34
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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.