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?

1 Answer 1


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())
  • 1
    Works like a charm. Thanks!
    – CNIDog
    May 20, 2019 at 20:15
  • 1
    @CNIDog - Most welcome, glad it helped :)
    – Joseph
    May 21, 2019 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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