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
35.7k5 gold badges77 silver badges151 bronze badges
asked Oct 26, 2016 at 4:59
1
  • 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? Commented Oct 26, 2016 at 5:03

2 Answers 2

18

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):
 layer.deleteFeatures(layer.allFeatureIds())
answered Oct 26, 2016 at 9:46
5
  • 1
    That works perfectly !! Commented Oct 26, 2016 at 11:50
  • @Sjs - Awesome, glad it worked =) Commented Oct 26, 2016 at 11:50
  • 4
    You could remove all features at once with layer.deleteFeatures( listOfIds ). Commented Oct 26, 2016 at 20:00
  • 1
    @GermánCarrillo - That is indeed a much better approach, many thanks ;) Commented Nov 7, 2016 at 10:08
  • 2
    For Qgis 3.2 instead of layer.deleteFeatures( listOfIds ) works layer.dataProvider().deleteFeatures( listOfIds ) Commented Dec 7, 2018 at 19:11
12

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
35.7k5 gold badges77 silver badges151 bronze badges
answered May 12, 2017 at 11:56
2
  • 1
    That's a nice new feature :) Commented May 12, 2017 at 11:59
  • 1
    It is not work in editing mode Commented Apr 8, 2019 at 9:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.