[GIS] PyQGIS refresh layer tree programmatically

filterlayertreepyqgisqgis

When programmatically applying a subset string to a vector layer (here: ax_flurstueck with object count 34265)

enter image description here

via

l = iface.activeLayer()
l.setSubsetString('gemarkungsnummer in ('2760','2765','2771','2780','2786','2800','2811','2817','2836')')

the map canvas refreshes automatically, but not the object count in the layer tree (displays still 34265 objects):

enter image description here

When moving the main window around or changing the width of the layer tree or something like that, the layer tree refreshes (21581 objects).

enter image description here

The question is, how to achieve this programmatically? I did not find something like:

QgsLayerTreeView.refesh()

in analogy to refreshing the map canvas. Am I missing something?

Best Answer

This is a quick response but this code work perfectly,and you can refresh featurecount on QgsLayerTreeView.

1:Option

l = iface.activeLayer()
l.setSubsetString('gemarkungsnummer in ('2760','2765','2771','2780','2786','2800','2811','2817','2836')')
qgisTView = qgis.utils.iface.layerTreeView()
actions=qgisTView.defaultActions ()
actions.showFeatureCount ()
actions.showFeatureCount ()

2: Option

Replicate core code in Python.

iface=qgis.utils.iface
l = iface.activeLayer()
l.setSubsetString('gemarkungsnummer in ('2760','2765','2771','2780','2786','2800','2811','2817','2836')')

mView= iface.layerTreeView()
node = iface.layerTreeView().currentNode()
nodeslist=mView.selectedLayerNodes()
newValue = node.customProperty("showFeatureCount", 0 ) 
for value in nodeslist:
    value.setCustomProperty("showFeatureCount", int(newValue));
Related Question