Tuesday, 12 February 2019

pyqgis - Setting feature attribute by name via QGIS python api?



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

Answer



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

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...