4

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?

1 Answer 1

7

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

4
  • @Hydrographer - Most welcome! Glad it helped :)
    – Joseph
    Commented Apr 1, 2016 at 9:47
  • 1
    Great! This worked for me. Commented Apr 19, 2019 at 11:32
  • @AmarKamthe - Glad to hear it :)
    – Joseph
    Commented Apr 23, 2019 at 9:19
  • for a specific layer if child.layerName() == has to be chanced into if child.name() ==
    – Klaus
    Commented May 2, 2023 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.