I'm looking for a way to write the feature count at the bottom of the Layer Name, is this possible? Is there a variable?
I know about the feature counting functionality built into QGIS and I know the Python Console command that applies feature counting to all groups, layers etc... but I don't need this.
In the image below I would like a variable to be inserted instead of the word HERE which then makes the feature count appear.
1 Answer 1
Here is a PyQGIS solution.
QgsVectorLayer
inherits a special method called setName()
from the QgsMapLayer
class.
Set the display name of the layer.
If it is a one-time action
For a single layer :
# imports
from qgis.core import QgsProject
# getting a layer by its id
layer = QgsProject.instance().mapLayer("LAYER_ID")
# getting layer's name
name = layer.sourceName()
# counting features in the layer
n = layer.featureCount()
# setting up a new name
layer.setName(f"{name} [{n}]")
For all vector vector layers shown in the Layers panel :
# imports
from qgis.core import QgsProject, QgsVectorLayer
# getting all vector layers' ids in the project
ids = [layer.id() for layer in QgsProject().instance().mapLayers().values() if isinstance(layer, QgsVectorLayer)]
# looping over each layer's id
for id in ids:
# accessing a layer by its id
layer = QgsProject.instance().mapLayer(id)
# getting layer's name
name = layer.sourceName()
# counting features in the layer
n = layer.featureCount()
# setting up a new name
layer.setName(f"{name} [{n}]")
However, if this operation happens more often, one should think of a more programmatic way of showing the feature count in the layer name.
As an alternative one can also proceed with a Python macro, like in this thread: Is it possible to have dynamic layer names in QGIS project?.
References: