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?
-
2Please 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– Fezter2016年10月26日 05:03:39 +00:00Commented Oct 26, 2016 at 5:03
2 Answers 2
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())
-
1
-
@Sjs - Awesome, glad it worked =)Joseph– Joseph2016年10月26日 11:50:43 +00:00Commented Oct 26, 2016 at 11:50
-
4You could remove all features at once with layer.deleteFeatures( listOfIds ).Germán Carrillo– Germán Carrillo2016年10月26日 20:00:01 +00:00Commented Oct 26, 2016 at 20:00
-
1@GermánCarrillo - That is indeed a much better approach, many thanks ;)Joseph– Joseph2016年11月07日 10:08:34 +00:00Commented Nov 7, 2016 at 10:08
-
2For Qgis 3.2 instead of layer.deleteFeatures( listOfIds ) works layer.dataProvider().deleteFeatures( listOfIds )Vadym– Vadym2018年12月07日 19:11:53 +00:00Commented Dec 7, 2018 at 19:11
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()
-
1That's a nice new feature :)Joseph– Joseph2017年05月12日 11:59:17 +00:00Commented May 12, 2017 at 11:59
-
1It is not work in editing modeMustafa Uçar– Mustafa Uçar2019年04月08日 09:42:17 +00:00Commented Apr 8, 2019 at 9:42
Explore related questions
See similar questions with these tags.