|

PyQGIS: Delete Features

Deleting features is a common operation in QGIS. It is easy to automate this task with Python, allowing you to quickly delete features based on any conditions you set.

First, select the layer from which you want to delete features. This line of code will select the first layer with the name ‘layer name’. You can replace ‘layer name’ with the name of your layer that is listed in the QGIS Table of Contents.

layers = QgsProject.instance().mapLayersByName('layer name')
layer = layers[0]

Save the layer capabilities to a variable. We will need to know what the layer capabilities are to make sure we can actually delete features from this layer

caps = layer.dataProvider().capabilities()

Get a list of all the features in the layer, and create an empty list. You will add the features you want to delete to this list.

feats = layer.getFeatures()
dfeats = []

This if statement will make sure your layer has the capability to delete features. Most layers have this capability. In the event an error is made or the layer doesn’t have the capability, this line of code will prevent an error or file corruption. The rest of the code will be written inside of the if statement.

if caps & QgsVectorDataProvider.DeleteFeatures:

Now you can loop through each feature in the layer and apply conditions to identify features you want to delete. The code below identifies features where the ‘GRID_CODE’ field in the attribute table is equal to 3. Once a feature to delete is identified, append it to the list of features to delete.

if caps & QgsVectorDataProvider.DeleteFeatures:
    for feat in feats:
        if feat['GRID_CODE'] == 3:
            dfeats.append(feat.id())

Finally, you can delete the list of features you’ve identified from the layer. This operation returns a result that you can check to make sure the delete operation happened properly. After the features are deleted trigger a repaint of the layer so that the features displayed in the map canvas are redrawn.

if caps & QgsVectorDataProvider.DeleteFeatures:
    for feat in feats:
        if feat['GRID_CODE'] == 3:
            dfeats.append(feat.id())
    res = layer.dataProvider().deleteFeatures(dfeats)
    layer.triggerRepaint()

Here is the finished code block. Watch the video below the code for a step-by-step demonstration of the process.

layers = QgsProject.instance().mapLayersByName('layer name')
layer = layers[0]
caps = layer.dataProvider().capabilities()
feats = layer.getFeatures()
dfeats = []

if caps & QgsVectorDataProvider.DeleteFeatures:
    for feat in feats:
        if feat['GRID_CODE'] == 3:
            dfeats.append(feat.id())
    res = layer.dataProvider().deleteFeatures(dfeats)
    layer.triggerRepaint()

Similar Posts