I would also think in terms of PyQGIS combined with editing the model by hand. There is a useful method variantToSource()
from the QgsProcessingUtils
class. After its implementation, one gets a pure QgsProcessingFeatureSource
-object that possesses a hasFeatures
method.
On the other side, one could handle the empty QgsProcessingFeatureSource
as an empty dictionary i.e. {}
, however, the temporary output will still be added. Therefore I am suggesting adding the QgsProcessingException
in this case to ignore empty temporary outputs.
So, in the end, your model may look as follows:
"""
Model exported as python.
Name : filterwfs
Group : Models
With QGIS : 33408
"""
from qgis.core import (QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingMultiStepFeedback,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterFeatureSink,
QgsProcessingException,
QgsProcessingUtils)
from qgis.utils import iface
import processing
class Filterwfs(QgsProcessingAlgorithm):
def name(self):
return 'filterwfs'
def displayName(self):
return 'filterwfs'
def group(self):
return 'Models'
def groupId(self):
return 'Models'
def createInstance(self):
return Filterwfs()
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterVectorLayer('input', 'INPUT', defaultValue=None))
self.addParameter(QgsProcessingParameterFeatureSink('output', 'OUTPUT', type=QgsProcessing.TypeVectorPolygon,
createByDefault=False, defaultValue=None))
def processAlgorithm(self, parameters, context, model_feedback):
# Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
# overall progress through the model
feedback = QgsProcessingMultiStepFeedback(1, model_feedback)
results = {}
outputs = {}
# Extract/clip by extent
alg_params = {
'INPUT': parameters['input'],
'EXTENT': iface.mapCanvas().extent(),
'CLIP': False,
'OUTPUT': parameters['output']
}
outputs['extract'] = processing.run("native:extractbyextent", alg_params, context=context, feedback=feedback,
is_child_algorithm=True)
results['Output'] = outputs['extract']['OUTPUT']
source = QgsProcessingUtils.variantToSource(results['Output'], context=context, fallbackValue=feedback)
if source.hasFeatures() > 0:
return results
else:
raise QgsProcessingException('Empty layer was not added.')
References: