TransWikia.com

PyQGIS: deleting selected features

Geographic Information Systems Asked on June 24, 2021

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 ?

One Answer

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)

Correct answer by ThomasG77 on June 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP