1

My objective is to add a new calculated field to the output layer from a processing script.

This layer is created as follows:-


source = self.parameterAsSource(
            parameters,
            self.INPUT,
            context
        )

(sink, dest_id) = self.parameterAsSink(
            parameters,
            self.OUTPUT,
            context,
            source.fields(),
            source.wkbType(),
            source.sourceCrs()
        )

I am then adding a feature to the sink layer from source in an iteration loop


 for current, feature in enumerate(source.getFeatures()):
      value = 1
      #I want to add value to feature as an attribute, how??
      sink.addFeature(feature, QgsFeatureSink.FastInsert)

How do I add the value attribute to the sink layer?

Should it be done when declaring sink?

4

Ok I managed it, bit hacky and I need to copy in other fields from feature

Declare the sink with new fields

new_fields = source.fields()
new_fields.append(QgsField('overlap', QVariant.Double))
(sink, dest_id) = self.parameterAsSink(
            parameters,
            self.OUTPUT,
            context,
            new_fields,
            source.wkbType(),
            source.sourceCrs()
)

Create a new feature and output

 new_feat = QgsFeature()
 new_feat.setGeometry(feature.geometry())
 new_feat.setFields(new_fields)
 new_feat['overlap'] = overlap
 sink.addFeature(new_feat, QgsFeatureSink.FastInsert)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.