11

I am developing a Python plugin for QGIS. In the QGIS map window, certain features of a vector layer are selected and those features are highlighted. Now I need to delete all the existing features from another vector layer without disturbing the current selection in the map window.

Is it possible to delete all the features of a vector layer without selecting them?

Taras
  • 32,823
  • 4
  • 66
  • 137
Sjs
  • 997
  • 1
  • 11
  • 23
  • 2
    Please rephrase your question to indicate where you're getting stuck. Avoid questions that begin with "Is it possible..." as the answer is most likely "Yes". What have you tried so far? – Fezter Oct 26 '16 at 05:03

2 Answers2

17

You could use the following code which is heavily based on the answer from this post: How to delete selected features in QGIS using Python

layer = iface.activeLayer()
with edit(layer):   
    for feat in layer.getFeatures():
        layer.deleteFeature(feat.id())

Edit:

Thanks to @GermánCarrillo, a more efficient method could be to delete all features at once:

layer = iface.activeLayer()
with edit(layer):
    listOfIds = [feat.id() for feat in layer.getFeatures()]
    layer.deleteFeatures( listOfIds )
Joseph
  • 75,746
  • 7
  • 171
  • 282
10

In QGIS 3 one can use the truncate() method of the QgsVectorDataProvider class.

Removes all features from the layer.

This requires either the FastTruncate or DeleteFeatures capability. Providers with the FastTruncate capability will use an optimised method to truncate the layer.

# referring to the original Vector layer
layer = QgsProject.instance().mapLayersByName("points")[0]

accessing Vector layer provider

provider = source_layer.dataProvider()

deleting all features in the Vector layer

provider.truncate()

Taras
  • 32,823
  • 4
  • 66
  • 137
Peter Petrik
  • 1,425
  • 13
  • 23