2

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 :

  1. I select manually the features of the shapefile A
  2. I select all the features of the shapefile B that intersects the selected features of shapefile A
  3. 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 ?

1 Answer 1

2

You may try the following to be sure you delete features after processing run really ended

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]
}

def callback:
    with edit(shapefileA):   
        for feat in shapefileA.selectedFeatures():
            shapefileA.deleteFeature(feat.id())

    with edit(shapefileB):   
        for feat in shapefileB.selectedFeatures():
            shapefileB.deleteFeature(feat.id())

processing.run('native:selectbylocation', alg_params, onFinish=callback)
1
  • Thanks for your reply Thomas ! Actually I solved my issue by integrating my script in a small plugin. I linked the first QPushButton to the selection and the second QPushButton to the deletion of the selected features
    – wanderzen
    Commented Mar 1, 2021 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.