Sunday, 13 August 2017

Deleting all Features of a Vector Layer in pyQGIS


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?



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 )

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...