algorithmprocessingqgispyqgis

PyQGIS, custom processing algorithm: How to use selected features only?


I want to create a custom processing algorithm with PyQGIS, which is able to take a vector layer as input (in this case of type point) and then do something with it's features. It's working well as long as I just choose the whole layer. But it doesn't work if I'm trying to work on selected features only.

I'm using QgsProcessingParameterFeatureSource to be able to work on selected features only. The option is shown and I can enable the checkbox. But when I'm executing the algorithm, I get NoneType as return of parameterAsVectorLayer.

Below you'll find a minimal working example to reproduce the problem:

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (
    QgsProcessing,
    QgsProcessingAlgorithm,
    QgsProcessingParameterFeatureSource
)

name = "selectedonly"
display_name = "Selected features only example"
group = "Test"
group_id = "test"
short_help_string = "Minimal working example code for showing my problem."

class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return ExampleProcessingAlgorithm()

    def name(self):
        return name

    def displayName(self):
        return self.tr(display_name)

    def group(self):
        return self.tr(group)

    def groupId(self):
        return group_id

    def shortHelpString(self):
        return self.tr(short_help_string)

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                'INPUT',
                self.tr('Some point vector layer.'),
                types=[QgsProcessing.TypeVectorPoint]
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        layer = self.parameterAsVectorLayer(
            parameters,
            'INPUT',
            context
        )
        return {"OUTPUT": layer}

If I'm working on the whole layer, the output is {'OUTPUT': <QgsVectorLayer: 'Neuer Temporärlayer' (memory)>}, which is what I would expect.

If I'm working on selected features only, my output is {'OUTPUT': None}, which doesn't makes sense to me. I selected some of the features before executing of course.

I'm using QGIS-version 3.22 LTR, if it's relevant.

Can anybody tell me what I'm doing wrong?


Solution

  • I would suggest you trying to use the method 'parameterAsSource' in the 'processAlgorithm' method.

    layer = self.parameterAsSource(
            parameters,
            'INPUT',
            context
        )