1

I'm working on a custom QGIS Processing algorithm, and I'd like to include an option for the user to process only the selected features in the input layer by using the checkbox "Selected Features Only" for QgsProcessingParameterFeatureSource, I spend hours trying to fix it but I don't see a way to get that. I'm using QGIS 3.22

Here's a simplified version of my script:

def initAlgorithm(self, config=None):
    self.addParameter(
        QgsProcessingParameterFeatureSource(
            self.INPUT,
            self.tr('Layer contendo pontos finais e iniciais de cada parcela'),
            [QgsProcessing.TypeVectorPoint]
        )
    )

def processAlgorithm(self, parameters, context, feedback): source_layer = self.parameterAsSource( parameters, self.INPUT, context, QgsProcessingFeatureSource.Flags() )

new_field_1 = processing.run("native:fieldcalculator", {
    'INPUT': source_layer.materialize(QgsFeatureRequest()),  # Use 'source_layer' directly
    'FIELD_NAME': 'groupkey',
    'FIELD_TYPE': 2,
    'FIELD_LENGTH': 25,
    'FIELD_PRECISION': 0,
    'FORMULA': 'concat("patio", \'-\', "orderparc")',
    'OUTPUT': 'memory:'
})


points_to_path_result = processing.run("native:pointstopath", {
    'INPUT': new_field_1['OUTPUT'],
    'CLOSE_PATH': True,
    'ORDER_EXPRESSION': '"Name"',
    'NATURAL_SORT': False,
    'GROUP_EXPRESSION': '"groupkey"',
    'OUTPUT': 'memory:'
}, context=context, feedback=feedback)

# rest of the scrit...

Taras
  • 32,823
  • 4
  • 66
  • 137
Matt_Geo
  • 1,050
  • 1
  • 10
  • 26
  • Can it help? https://gis.stackexchange.com/questions/311149/how-to-run-qgis-algorithms-with-selected-features – RainForest Apr 06 '23 at 14:41

1 Answers1

0

Try this code:

input_layer = QgsProcessingFeatureSourceDefinition('insert_file_path_here',                                                       
                                                   selectedFeaturesOnly=True,
                                                   featureLimit=-1,
                                                   geometryCheck=QgsFeatureRequest.GeometryAbortOnInvalid)
processing.run("native:fieldcalculator", {
                'INPUT': input_layer,
                'FIELD_NAME': 'FIELD_NAME',
                'FIELD_TYPE': 0,
                'FIELD_LENGTH': 0,
                'FIELD_PRECISION': 0,
                'FORMULA': '1',
                'OUTPUT': 'TEMPORARY_OUTPUT'
                })
Taras
  • 32,823
  • 4
  • 66
  • 137
Comrade Che
  • 7,091
  • 27
  • 58