5

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?

HeikkiVesanto
17.1k2 gold badges49 silver badges82 bronze badges
asked Oct 22, 2019 at 14:26

1 Answer 1

3

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)
Taras
35.8k5 gold badges77 silver badges151 bronze badges
answered Oct 22, 2019 at 16:10
0

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.