PyQGIS – How to Delete All Features of a Vector Layer

deletepyqgisqgis-python-consolevector-layer

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?

Best Answer

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 )