5

Is it possible to use an optional variable (value2) like

...
@qgsfunction(args='auto', group='Custom')
def my_test(value1, value2=True, feature, parent)
....

in a custom function? Using QGIS 3.8

...likeenter image description here

2 Answers 2

2

Not sure of a direct way but there is the handlesnull flag which when set to true would let you input NULL as a parameter value.

...
@qgsfunction(args='auto', group='Custom', handlesnull=True)
def my_test(value1, value2, feature, parent):
...

You might want to include some logic in your code to determine what happens when a parameter value is NULL.

0

I found a workaround to accept optional argument with default value. You need to accept any number of arguments then parse the arguments yourself

To do so, in the decorator set args to '-1' so any number of arguments are accepted, then the first parameter of your function will be a list of all the arguments

@qgsfunction(args='-1', group='Custom')
def my_test(values, feature, parent):
    if len(values) < 1 or len(values) > 2:
        parent.setEvalErrorString("Error: invalid number of arguments in the function my_test")
        return
    
    value1 = values[0]
    value2 = values[1] if len(values) == 2 else 'Default Value'
    
    #your own code here

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.