Skip to content Skip to sidebar Skip to footer

Parent A Qtreewidgetitem To An Existing Qtreewidgetitem To Second Column Maintaining The First Column

I created a QTreeWidget and parented a QTreeWidgetItem using the QTreeWidget.addTopLevelItem method. The QTreeWidgetItem are parented to each other with QTreeWidgetItem.addChild.

Solution 1:

You could set the check boxes to the second column in your QTreeWidget and swap the first and second sections of the header, e.g.

from PySide2 import QtWidgets, QtCore

class MyItem(QtWidgets.QTreeWidgetItem):
    def __init__(self, label):
        super().__init__([label, ''])
        self.setCheckState(1, QtCore.Qt.Unchecked)
        self.setFlags(self.flags() | QtCore.Qt.ItemIsAutoTristate)

class MyTree(QtWidgets.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setColumnCount(2)
        self.header().swapSections(1,0)
        self.header().resizeSection(1, 80)

if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    tree = MyTree()
    tree.setHeaderLabels(['label', 'checked'])
    items = [MyItem(f'item {i}') for i in range(6)]
    tree.insertTopLevelItems(0, items)
    for i, item in enumerate(items):
        for j in range(4):
            items[i].addChild(MyItem(f'item {i}-{j}'))
    tree.show()
    app.exec_()

Note that I've also set QtCore.Qt.ItemIsAutoTristate to automatically update the checked state of the parent/children of an item when its checked state changes. screenshot of tree with checkboxes on the left

Post a Comment for "Parent A Qtreewidgetitem To An Existing Qtreewidgetitem To Second Column Maintaining The First Column"