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?
setExpanded(False)first? – Ben W Jan 05 '22 at 13:05