I have a problem with QgsFeature.setAttributes() method, I have tried something like the code below:
some_layer = iface.activeLayer()
fields = some_layer.fields()
extra_fields = [QgsField('field1',QVariant.String), QgsField('field2', QVariant.String)]
for field in extra_fields:
fields.append(field)
some_fts = some_layer.getFeatures()
for some_ft in some_fts:
attrs = some_ft.attributes()
new_feature = QgsFeature(fields)
new_feature.setAttributes(attrs)
new_feature['field1'] = 'some text'
When this is done, the new feature 'field1' attribute has value NULL. When I out-comment the line:
#new_feature.setAttributes(attrs)
the new feature 'field1' attribute has value 'some text', ofcourse in that case all the other attributes are nulls.
Does anyone know why accessing the attributes, after setAttributes method has been used, doesn't work?
1 Answer 1
You need to set the attributes in one go.
Can you try:
for some_ft in some_fts:
attrs = some_ft.attributes()
new_feature = QgsFeature(fields)
new_feature.setAttributes(attrs)
attrs.append('some text')
new_feature.setAttributes(attrs)