2

I'd like to write a simple algorithm to sum up a numeric column in an input vector layer. I can't connect the FIELD input to the SOURCE layer. I tried to add 'parent' parameter but it is unknown keyword argument, however it is listed in the algfactory.py. Here is my code:

from qgis import processing
from qgis.processing import alg
from qgis.core import QgsProject

@alg(name='AlgSumCol', label='Sum of a column', group='examplescripts',
     group_label='Example scripts')
@alg.input(type=alg.SOURCE, name='INPUT', label='Input vector layer')
@alg.input(type=alg.FIELD, name='FIELD', label='Input field', parent='INPUT')
@alg.output(type=alg.NUMBER, name='SUM', label='Sum')

def AlgSumCol(instance, parameters, context, feedback, inputs):
    """ Sum up a numeric column """
    print(type(instance))
    source = instance.parameterAsSource(parameters, 'INPUT', context)
    field_name = instance.parameterAsString(parameters, 'FIELD', context)
    features = source.getFeatures()
    total = 0
    for feat in features:
        total += feat[field_name]
    return {'SUM': total}

I would like to have the names of numeric attributes of the INPUT layer in the FIELD to select, but I get an error: TypeError: 'parent' is an unknown keyword argument.

If I remove parent keyword argument and change alg.FIELD to arg.STRING, it works but I have to fill the column name manually.

How can I connect the two inputs and limit to numeric attributes? I can do it using the QgsProcessingAlgorithm class, but I would like to use @arg shorter code.

Your Answer

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

Browse other questions tagged or ask your own question.