3

PyQGIS 2 has a function to expand/collapse a layers with a subset of styles in the Layers panel as follows:

self.iface.legendInterface().setLayerExpanded(self.segments_layer, False)

I know that in PyQGIS 3 self.iface.legendInterface() has been replaced by gsProject.instance().layerTreeRoot() but making that switch in this case produces an error:

AttributeError: 'QgsLayerTree' object has no attribute 'setLayerExpanded'

What is the appropriate replacement for setLayerExpanded in PyQGIS 3?

Taras
  • 32,823
  • 4
  • 66
  • 137
CNIDog
  • 479
  • 3
  • 13

2 Answers2

4

You can access it from the QgsLayerTreeNode::setExpanded() function:

root = QgsProject.instance().layerTreeRoot()
layer = QgsProject.instance().mapLayersByName('Layer_Name')[0]
myLayerNode = root.findLayer(layer.id())
myLayerNode.setExpanded(True)
Joseph
  • 75,746
  • 7
  • 171
  • 282
0

If you want to clean up a giant list of expanded group layers in the table of contents, here's a few lines of PyQGIS that'll do the trick (i.e. collapse all group layers):

root = QgsProject.instance().layerTreeRoot()
nodes = root.children()

for n in nodes: if isinstance(n, QgsLayerTreeGroup): if n.isExpanded() == True: n.setExpanded(False) print(f"Layer group '{n.name()}' now collapsed.")

grego
  • 1,043
  • 7
  • 18