I am developing a python plugin for QGIS. In 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 current selection in the map window. Is it possible to delete all the features of a vector layer without selecting them?

  • 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 5:03

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():


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 )
  • 1
    That works perfectly !!
    – Sjs
    Oct 26 '16 at 11:50
  • @Sjs - Awesome, glad it worked =)
    – Joseph
    Oct 26 '16 at 11:50
  • 3
    You could remove all features at once with layer.deleteFeatures( listOfIds ). Oct 26 '16 at 20:00
  • 1
    @GermánCarrillo - That is indeed a much better approach, many thanks ;)
    – Joseph
    Nov 7 '16 at 10:08
  • 2
    For Qgis 3.2 instead of layer.deleteFeatures( listOfIds ) works layer.dataProvider().deleteFeatures( listOfIds )
    – Vadym
    Dec 7 '18 at 19:11

In QGIS3 you can use truncate()

bool QgsVectorDataProvider::truncate()

Removes all features from the layer.

  • 1
    That's a nice new feature :)
    – Joseph
    May 12 '17 at 11:59
  • 1
    It is not work in editing mode Apr 8 '19 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.