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.
-
3You need to register the new attribute on the layer level, not the feature.bugmenot123– bugmenot1232021年12月06日 17:08:20 +00:00Commented Dec 6, 2021 at 17:08
1 Answer 1
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)
Explore related questions
See similar questions with these tags.