In the QGIS GUI, the select-by-location algorithm has a choice to only use the selected features from the INTERSECT layer. How can I do this (or use any other algorithm) in a python script for QGIS 3? I do not want to save temporal layer as mentioned in Run QGIS Model on selected features only?
I have been running this script but it does not use the selected features.
import processing
input_vlayer = 'Some path'
intersect_vlayer = 'Some path'
input_vlayer = iface.addVectorLayer(input_vlayer, 'input_vlayer', 'ogr')
intersect_vlayer = iface.addVectorLayer(intersect_vlayer,
'intersect_vlayer', 'ogr')
# Pass the first 5 features
for i in range(5):
# Select the features
intersect_vlayer.select(i)
# Set input params
params = {'INPUT':input_vlayer,
'PREDICATE':0,
'INTERSECT':intersect_vlayer, # USE HERE THE SELECTED FEATURES
'METHOD':0}
result = processing.run("qgis:selectbylocation", params)
# Remove the current selection and then pass to the next one
intersect_vlayer.removeSelection()
Also, from QGIS select by location doesn't use selected features only they mentioned to enable [Processing] > [Options] > [General] > [Use only selected features]. However I can't see this option in my qgis version. I'm using Madeira 3.4.3
Answer
For only use selected feature use QgsProcessingFeatureSourceDefinition
https://qgis.org/api/classQgsProcessingFeatureSourceDefinition.html
your code,but the input is only selected features
import processing
input_vlayer = 'Some path'
intersect_vlayer = 'Some path'
input_vlayer = iface.addVectorLayer(input_vlayer, 'input_vlayer', 'ogr')
intersect_vlayer = iface.addVectorLayer(intersect_vlayer,
'intersect_vlayer', 'ogr')
for i in range(5):
# Select the features
intersect_vlayer.select(i)
# Set input params
params = {'INPUT':input_vlayer,
'PREDICATE':0,
'INTERSECT':QgsProcessingFeatureSourceDefinition(intersect_vlayer.id(), True), # USE HERE THE SELECTED FEATURES
'METHOD':0}
result = processing.run("qgis:selectbylocation", params)
# Remove the current selection and then pass to the next one
intersect_vlayer.removeSelection()
No comments:
Post a Comment