0

I am writing a processing algorithm and I would like to return a feature sink as an output, but without treating it as a parameter. The point is I want to just add it to the table of content as a temporary layer, without showing it in the parameters window. However, I can't find any other way to create the feature sink other than by declaring parameter QgsProcessingParameterFeatureSink and referencing it by self.parameterAsSink.

Is there a way to return a feature sink as an output ? Or maybe it should be done with another approach?

2

OK, I've found a workaround for given task without using feature sink. I am not sure if this is the best approach, but seems to get the job done.

Here is a simplified code:

def initAlgorithm(self, config=None):
    # your parameters...
    self.addOutput(
        QgsProcessingOutputVectorLayer(self.NEW_LAYER, self.tr('my_new_layer'), QgsProcessing.TypeVectorAnyGeometry))

def processAlgorithm(self, parameters, context, feedback):
    # ...
    # copying layer
    layer.selectAll()
    layer_2 = processing.run("native:saveselectedfeatures", {'INPUT': layer, 'OUTPUT': 'memory:'})['OUTPUT']
    layer.removeSelection()

    # editing copy of layer
    with edit(layer_2):
        for i in layer_2.getFeatures():
            if i.attribute("something") not in what_i_want:
                layer_2.deleteFeature(i.id())

    # adding layer to load on completion
    context.temporaryLayerStore().addMapLayer(layer_2)
    context.addLayerToLoadOnCompletion(layer_2.id(),
                                       QgsProcessingContext.LayerDetails(QgsProcessingContext.LayerDetails(
                                           'my_new_layer',
                                           context.project(),
                                           self.NEW_LAYER)))
    # returning output
    return {self.NEW_LAYER: layer_2}

So it goes like that:

  1. in initAlgorithm you need to add output definition
  2. Work on QgsVectorLayer object (in my case a copy of another layer). You can add and delete features as in feature sink
  3. Add your new layer to load on completion
  4. Return the output. Layer will show in TOC as temporary layer, where user can take it or leave it without the need to specify anything before processing. For me it was essential to have such feature as my script is producing a bunch of minor layers, that may or may not be important for user.

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.