[GIS] Show QGIS feature count via console on existing layers

pyqgispythonqgis

I want to make a script that toggles feature count on for all vector layers. I followed the following article: Show feature count of layer via Python console / PyQGIS.

Instead of adding new layers with feature count I'd like to switch on GUI feature count on existing layers. I adapted the code in the article so that myLayer is substituted with an existing layer that I retrieved by listing the layers.

The new layer made by the unadapted code to myLayerNode:

<qgis._core.QgsLayerTreeLayer object at 0x000000001FEC4950>

The existing layer after saving it in myLayerNode:

 <qgis._core.QgsLayerTreeLayer object at 0x000000001FEC49D8>

The new layer feature count can be toggled on/off using:

myLayerNode.setCustomProperty("showFeatureCount", True)

To my knowledge this should work but it doesn't…

#Make a list of layers
qgis.utils.iface.iface = iface
layers = qgis.utils.iface.iface.legendInterface().layers()

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

## pick one layer to change featurecount
myLayer = layers[5]
myLayerNode = QgsLayerTreeLayer(myLayer)
#root.insertChildNode(5, myLayerNode)

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

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

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

Any idears?

Best Answer

Not completely sure why your code doesn't work but the following works for me in the Python console:

  • To see the feature count for a specific layer:

    root = QgsProject.instance().layerTreeRoot()
    for child in root.children():
        if isinstance(child, QgsLayerTreeLayer):
            if child.layerName() == "LAYER_NAME":
                child.setCustomProperty("showFeatureCount", True)
    

    Feature count of specific layer


  • To see the feature count of all layers:

    root = QgsProject.instance().layerTreeRoot()
    for child in root.children():
        if isinstance(child, QgsLayerTreeLayer):
            child.setCustomProperty("showFeatureCount", True)
    

    Feature count of all layers

Related Question