Search code examples
pythonpython-3.xqtpyqt5qtreewidget

How to restore to normal to Qtreewidget Pyqt5?


I just made a program with QTreeWidget.But I want to restore it to normal when I click a button,I mean it should be same as when it started. I learned how to remove the selected section that appears with a blue horizontal line.by

mytreeview.clearSelection()

check the imagethe blue tab line But if anyone expand the column width, check the 2nd imageenter image description here , "Type" column width has been increased from 1st picture.Then the question is how can i set it to normal means to my default value shown in picture-1 and imagine someone change the position of "Date Modified" to the place of "Size" column by dragging(position exchanged). Then How can i reset it to normal by pressing a button? This is some fundamental doubts about Qtreewidget so i have no code to write here. Any help will be appreciated Thank u


Solution

  • You can collect and store the section sizes using sectionSize() and restore it with resizeSection().

    In order to restore the original logical indexes, just check the visualIndex() and if it doesn't match the logical index then use moveSection().

            # ...
            header = self.table.horizontalHeader()
            self.sectionSizes = [header.sectionSize(s) for s in range(header.count())]
    
        def resetSections(self):
            header = self.table.horizontalHeader()
            for section, size in enumerate(self.sectionSizes):
                if header.visualIndex(section) != section:
                    header.moveSection(header.visualIndex(section), section)
                header.resizeSection(section, size)
    

    I strongly suggest you to carefully read and study the documentation about QTableWidget (and its inherited classes: QTableView and QAbstractItemView) along with QHeaderView, as everything you were asking is clearly explained in those pages.