QGIS PyQGIS – Show Feature Count of Layer via Python Console

pyqgisqgis

When working with vector layers in QGIS, I can display the feature count of a layer and, if applicable, the feature count per attribute category (e.g. when using categorized or graduated styling) via the context menu of the layer. The counts are added to the layer title that is displayed in the layer widget.

Get feature count in QGIS

How can I set activate this feature via the Python console/running a script? Looking through the API docs, I found a method to get the feature counts and further use them in your script. However, how can I display them as they would show when using the GUI?

It is probably possible somehow by retrieving the feature count as described above and then changing the layer widget symbology, adding the count to the title. However, this is rather cumbersome, so I wonder if there is a direct way to achieve this? If not, how would this best be done manually?

Best Answer

That is pretty simple by using custom properties by the setCustomProperty() method.

The below example adds a memory layer to the legend and set the "showFeatureCount" property to True (you can run it from pyqgis console):

## create the memory layer and add to the registry
myLayer = QgsVectorLayer("Point", "myLayer", "memory")
QgsMapLayerRegistry.instance().addMapLayer(myLayer, False)

## reference to the layer tree
root = QgsProject.instance().layerTreeRoot()

## adds the memory layer to the layer node at index 0
myLayerNode = QgsLayerTreeLayer(myLayer)
root.insertChildNode(0, myLayerNode)

## set custom property
myLayerNode.setCustomProperty("showFeatureCount", True)

To get a specific property of the current layer (node layer) in layer tree you can use customProperty() or customProperties() to get all the stored properties for that layer:

myLayerNode.customProperty("showFeatureCount")
## the result is True

myLayerNode.customProperties()
## the result is a list [u'showFeatureCount']