Optional parameters in QGIS Processing scripts & models
Remember the good old times when all parameters in Processing were mandatory?
Inputs and outputs are fixed, and optional parameters or outputs are not supported. [Graser & Olaya, 2015]
Since QGIS 2.14, this is no longer the case. Scripts, as well as models, can now have optional parameters. Here is how for QGIS 3:
When defining a Processing script parameter, the parameter’s constructor takes a boolean flag indicating whether the parameter should be optional. It’s false by default:
class qgis.core.QgsProcessingParameterNumber( name: str, description: str = '', type: QgsProcessingParameterNumber.Type = QgsProcessingParameterNumber.Integer, defaultValue: Any = None, optional: bool = False, minValue: float = -DBL_MAX+1, maxValue: float = DBL_MAX)
(Source: http://python.qgis.org/api/core/Processing/QgsProcessingParameterNumber.html)
One standard tool that uses optional parameters is Add autoincremental field:
From Python, this algorithm can be called with or without the optional parameters:
When building a model, an optional input can be assigned to the optional parameter. To create an optional input, make sure to deactivate the mandatory checkbox at the bottom of the input parameter definition:
Then this optional input can be used in an algorithm. For example, here the numerical input optional_value is passed to the Start values at parameter:
You can get access to all available inputs by clicking the … button next to the Start values at field. In this example, I have access to values of the input layer as well as the optional value:
Once this is set up, this is how it looks when the model is run:
You can see that the optional value is indeed Not set.