2

I have tried reading the docs located here but there is no mention of any method that allows you to add new attributes to the feature only modify existing ones.

Something along the lines of:

QgsFeature.addAttribute(name='Score')

A snippet from my code where I attempted to find a workaround is shown below:

 #create score field by copying fields from origin
 #and append the new score field
 fields = QgsFields(source.fields())
 fields.append(QgsField('Score', QVariant.Int))
 for feature in features:
 #set score for each feature
 score = 12
 #set score attribute
 feature.setFields(fields, initAttributes=False)
 feature['Score'] = score
 #add feature to the output
 sink.addFeature(feature, QgsFeatureSink.FastInsert)

However, when I run the plugin I am making, there is no errors but the output has no attribute named Score.

Note: the score variable is not going to be equal to 12 for each feature I just changed it to be like that for simplicity. It will actually be calculated for each feature based on the features in the source layer.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Dec 6, 2021 at 14:42
1
  • 3
    You need to register the new attribute on the layer level, not the feature. Commented Dec 6, 2021 at 17:08

1 Answer 1

3
fields = lyr.fields()
# create a field instance
name = 'Score'
new_field = QgsField(name, QVariant.Int)
# open an edit session, it closes automatically after the block is executed
with edit(lyr):
 # add new field to the layer if it does not already exist
 if name not in fields.names(): 
 lyr.addAttribute(new_field)
 lyr.updateFields()
 # get the index of the new field
 idx = fields.indexFromName(name)
 for f in lyr.getFeatures():
 lyr.changeAttributeValue(f.id(), idx, 12) # (feature id, field index, value)
answered Jan 24, 2022 at 1:18

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.