3

I'm developing a Python plugin for QGIS. My goal is to add a layer group and then add a vector layer to it. The group is collapsed by default, and I'd like to expand it. But the setExpanded() method does not seem to have any effect until I expand the group via the GUI. Here's my code:

self.layer_group = self.layer_tree_root.insertGroup(0, self.plugin_name)
# To be added to group, layer has to be added to project first
self.project.addMapLayer(layer, addToLegend=False)  # layer is defined elsewhere in the code
# Explcitly add layer at position 0 or else it adds it to bottom
self.layer_group.insertLayer(0, layer)
self.layer_group.setExpanded(True)

The group stays collapsed. Printing self.layer_group.isExpanded() outputs True before and after calling self.layer_group.setExpanded(True). If I monitor the state change by connecting the self.layer_group.expandedChanged signal to a printing function, it doesn't print anything, so I conclude setExpanded() calls are ignored. But if I expand the group via a click in the GUI, and then call setExpanded() from the console, it all starts working fine.

Why are calls to setExpanded() ignored and what 'unmutes' them after I expand the group in the GUI?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Grigory Nedaev
  • 315
  • 1
  • 7
  • 1
    Seems the same issue (but opposite): https://gis.stackexchange.com/questions/420255/how-to-collapse-legend-in-toc-via-pyqgis The solution- call setExpanded(False) first? – Ben W Jan 05 '22 at 13:05
  • Thank you, PolyGeo, it works! Looks like a bug though. – Grigory Nedaev Jan 05 '22 at 14:01

1 Answers1

2

Turns out, you have to call setExpanded(False) first (seems like a bug). Then it works fine. More details here:

How to collapse legend in ToC via PyQGIS?

Grigory Nedaev
  • 315
  • 1
  • 7