QGIS Python Programming Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

Removing data from a vector layer

In this recipe, we'll completely remove a feature, including its 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 the following URL:

https://github.com/GeospatialPython/Learn/raw/master/NYC_MUSEUMS_GEO.zip

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, we load and validate the layer:
            vectorLyr =  QgsVectorLayer('/qgis_data/nyc/NYC_MUSEUMS_GEO.shp',
                                        'Museums' , "ogr") 
            vectorLyr.isValid() 
    
  4. Next, we specify a Python list containing feature IDs. In this case, we have two:
            vectorLyr.dataProvider().deleteFeatures([22, 95]) 
    

How it works...

This operation couldn't be simpler and better designed. There are a number of ways we could programmatically fill a Python list with feature IDs. Then, we just pass that list to the layer data provider and we are done. Note that the IDs are not stored with the data. They are dynamically assigned when the layer is loaded. If you remove the layer and re-add it, the IDs will be sequential without any missing values.