I have been facing issues trying to achieve a very simple task which consists in deleting selected features with pyqgis.
Here is a sample of my code :
- I select manually the features of the shapefile A
- I select all the features of the shapefile B that intersects the selected features of shapefile A
- I try to delete all the selected features of the shapefiles A and B
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
import processing
iface.actionSelect().trigger()
shapefileA= iface.activeLayer()
shapefileA.selectedFeatures()
shapefileB= QgsProject.instance().mapLayersByName('shapefileB')[0]
# SelectByLocation:
alg_params = {
'INPUT': shapefileB,
'INTERSECT': QgsProcessingFeatureSourceDefinition(shapefileA.id(), True),
'METHOD': 0,
'PREDICATE': [0]
}
processing.run('native:selectbylocation', alg_params)
with edit(shapefileA):
for feat in shapefileA.selectedFeatures():
shapefileA.deleteFeature(feat.id())
with edit(shapefileB):
for feat in shapefileB.selectedFeatures():
shapefileB.deleteFeature(feat.id())
The problem is that the script doesn't work instantly, I need to run it twice to make it work ! (If I run it once it seems it only selects the features of the shapefiles A and B but I have to run in another time for the delete of the features of shapefile A and B to be effective...)
Does someone know what I'm doing wrong ?