Saturday, 10 August 2019

pyqgis - Run QGIS Model on selected features only?


Would it be possible to run a script in a QGIS model so that it only runs on selected features from an input layer? I don't want to use the option in the toolbox options as I have other models that require to run without selections.


I just a model to only run on selected features in the input layer and return an error if no feature is selected. I'm thinking a script added immediately after the input in the model?



Answer




I think the answer by @underdark ♦ is correct in that you could use the Save selected features algorithm. However, as you mentioned, if no features are selected then it saves all features.


Building on from your previous question, we could add another if statement to the script to check if any features are selected. If yes then run the mentioned algorithm, otherwise show an error:


##Example=name
##input_layer=vector
##output=output vector

from qgis.utils import iface
from qgis.gui import QgsMessageBar

layer = processing.getObject(input_layer)

# Add your names into the list within single quotes
allowed_layers = ['map', 'layerName2', 'layerName3']

if layer.name() in allowed_layers:
if layer.selectedFeatures():
processing.runalg('qgis:saveselectedfeatures', layer, output)
else:
iface.messageBar().pushWidget(iface.messageBar().createMessage( u'No features selected' ), QgsMessageBar.WARNING, 3)
else:
iface.messageBar().pushWidget(iface.messageBar().createMessage( u'Layer not allowed' ), QgsMessageBar.WARNING, 3)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...