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?

asked Mar 30, 2016 at 19:05

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

answered Mar 31, 2016 at 11:19
4
  • @Hydrographer - Most welcome! Glad it helped :) 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 :) Commented Apr 23, 2019 at 9:19
  • for a specific layer if child.layerName() == has to be chanced into if child.name() == Commented May 2, 2023 at 16:40

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.