4

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?

Taras
35.8k5 gold badges77 silver badges152 bronze badges
asked Nov 8, 2019 at 7:06
2

1 Answer 1

2

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.")
answered Jul 1 at 9:28

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.