PyQGIS – Collapsing Legend in Table of Contents

pyqgispyqttable of contents

I am creating QGIS simple plugin which adds and set styles. It works like a charm, however i want to collapse all legends(categories) from styles in given layer i tried

            layer.setAutoRefreshEnabled(True)
            layerNode = self.root.findLayer(layer.id())
            layerNode.setExpanded(False)

but it seems to take no effect. As you can see in code snippet i am loading one layer after another so i decided to use this method in forloop to collapse every loaded layer but it does nothing. In layerNode is stored QgsLayerTreeLayer but setExpanded() takes no effect nor error. What is the trick? I found a solution in this thread, but i though that passing setExpanded directly in forloop would be better than creating another method.

def add_lidar(self,pos):
    if AutoProjekt.get_lidar_dir.has_been_called:
        selected = [item.text() for item in self.dlg.lidarList.selectedItems()]
        if len(selected) > 0:
            # ProgressBar
            self.dialog, self.bar = self.progdialog(0)
            self.bar.setValue(0)
            self.bar.setMaximum(100)
            fb = QgsProcessingFeedback()
            fb.progressChanged.connect(self.progress_changed)
            QApplication.processEvents()

            shapeGroup = self.root.insertGroup(pos,'LIDAR')
            selected.sort()
            count = len(selected)
            for i,filename in enumerate(selected):
                progValue = i+1
                splitted = filename.split(sep=' dirs:')
                name = splitted[0].lower()
                path = splitted[1]
                #if name in self.LIDAR:
                layer = QgsVectorLayer(path,name)
                
                if self.dlg.styleCheckBox.isChecked() and name in self.LIDAR:
                    self.set_style(layer, self.POLYGON, self.style['LIDAR'], name)
                    self.set_style(layer, self.POINT, self.style['LIDAR'], name)
                    self.set_style(layer, self.LINE, self.style['LIDAR'], name)

                QgsProject.instance().addMapLayer(layer,False)
                shapeGroup.insertChildNode(1,QgsLayerTreeLayer(layer))

                layer.setAutoRefreshEnabled(True)
                layerNode = self.root.findLayer(layer.id())
                layerNode.setExpanded(False)

                progress = progValue / float(count) * 100  
                self.bar.setValue(progress)  
                QApplication.processEvents() 

            time.sleep(0.5)  
            self.dialog.close()  
            self.bar.setValue(0)

I have found that layer has status isExpanded = False even in ToC it appears to be expanded.

Best Answer

I have found solution, but it looks silly. Layer after added has isExpanded value set to False even though in ToC appears to be expanded. By setting status of node to True then to False it takes effect in ToC:

layerNode = self.root.findLayer(layer.id())
layerNode.setExpanded(True)#added TRUE
layerNode.setExpanded(False)

I do not know why it happens that way. I thought that layer.setAutoRefreshEnabled(True) would solve everything.