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
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)
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)
-
@Hydrographer - Most welcome! Glad it helped :)Joseph– Joseph2016年04月01日 09:47:11 +00:00Commented Apr 1, 2016 at 9:47
-
1Great! This worked for me.Amar Kamthe– Amar Kamthe2019年04月19日 11:32:10 +00:00Commented Apr 19, 2019 at 11:32
-
@AmarKamthe - Glad to hear it :)Joseph– Joseph2019年04月23日 09:19:45 +00:00Commented Apr 23, 2019 at 9:19
-
for a specific layer if child.layerName() == has to be chanced into if child.name() ==Klaus– Klaus2023年05月02日 16:40:05 +00:00Commented May 2, 2023 at 16:40