Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
About the Author
About the Reviewers

Deleting a vector layer feature

In this recipe, we'll completely remove a feature, including the geometry and attributes, from a layer.

Getting ready

You will need the New York City museums' shapefile used in other recipes, which you can download as a ZIP file from

Extract this shapefile to /qgis_data/nyc.

How to do it...

All we need to do is load the layer and then delete the desired features by ID, using the layer's data provider:

  1. Start QGIS.

  2. From the Plugins menu, select Python Console.

  3. First, load and validate the layer:

    vectorLyr =  QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp', 'Museums' , "ogr")
  4. Next, specify a Python list containing feature IDs. In this case, we have two:

    vectorLyr.dataProvider().deleteFeatures([ 22, 95 ])

How it works...

This operation cannot be simpler or better designed. There are a number of ways in which we can programmatically fill a Python list with feature IDs. For example, we...