0

In QGIS, I try to write a script for a custom toolbox. I'm using the processing framework logic and following official documentation. I add an input vector layer, but I can't handle it has a QgsVectorLayer.

For example when I wan't to apply a filter to the selected layer I have an error message:

AttributeError: 'QgsProcessingFeatureSource' object has no attribute 'setSubsetString'

Here is an extract of my script:

class DissolveProcessingAlgorithm(QgsProcessingAlgorithm):
    INPUT = 'INPUT'
    ...

def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT,
                self.tr('Input layer'),
                [QgsProcessing.TypeVectorAnyGeometry]
            )
        )

def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(
            parameters,
            self.INPUT,
            context
        )    
        # Filter
        filter_value = '1'
        source.setSubsetString('"my_field"=\'%s\'' % filter_value)

How to handle QgsProcessingParameterFeatureSource as a vector layer has defined in initAlgorithm method ?

2
  • 2
    Use the materialize() method to return an in-memory vector layer from the QgsProcessingFeatureSource object.
    – Ben W
    Sep 20, 2023 at 23:49
  • That's the good way. I used new_layer = source.materialize(QgsFeatureRequest().setFilterFids(source.allFeatureIds())). After this I can do new_layer.setSubsetString('"my_field"=\'%s\'' % filter_value)
    – GeoGyro
    Sep 22, 2023 at 13:40

1 Answer 1

0

Create a new vector layer and copy what you need to it. There's no point in modifying the input.

I recommend to check the plugin builder template https://github.com/g-sherman/Qgis-Plugin-Builder/blob/master/plugin_templates/processing_provider/template/module_name_algorithm.tmpl

(install 'plugin builder' plugin)

1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 20, 2023 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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