I am working on intersections of a number of buffers with one another. When two particular buffers have no intersection, applying intersection function on them produces an empty layer which I want to delete. But how do I check if the intersection result produced is an empty layer or not? Is there any inbuilt function which I can use in my code?
-
3@Mr.Che, better this one: qgis.org/pyqgis/3.6/core/…Germán Carrillo– Germán Carrillo2019年11月08日 08:11:44 +00:00Commented Nov 8, 2019 at 8:11
-
qgis.core.QgsVectorLayer.hasFeatures() method qgis.org/pyqgis/master/core/…Comrade Che– Comrade Che2025年07月01日 12:46:21 +00:00Commented Jul 1 at 12:46
1 Answer 1
There are several approaches available to identify whether a vector layer is empty:
Solution 1: .hasFeatures()
method of the QgsVectorLayer
class
Determines if this vector layer has features.
Since QGIS 3.4
from qgis.core import QgsProject, Qgis
layer = QgsProject.instance().mapLayersByName("BW — Empty")[0]
if layer.hasFeatures() == 0:
# or if layer.hasFeatures() == Qgis.FeatureAvailability.NoFeaturesAvailable:
print(f"The layer '{layer.name()}' is empty.")
See also the return Qgis.FeatureAvailability.NoFeaturesAvailable
(since QGIS 3.36) of the .hasFeatures()
method.
Solution 2: .featureCount()
method of the QgsVectorLayer
class
Returns feature count including changes which have not yet been committed If you need only the count of committed features call this method on this layer's provider.
from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName("BW — Empty")[0]
if layer.featureCount() < 1:
print(f"The layer '{layer.name()}' is empty.")
It implements the QgsFeatureSource
class.
Solution 3: .empty()
method of the QgsVectorDataProvider
class
Returns
True
if the layer does not contain any feature
Since QGIS 3.4
from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName("BW — Empty")[0]
provider = layer.dataProvider()
if provider.empty():
print(f"The layer '{layer.name()}' is empty.")