0

I am using QTreeView rather than QTreeWidget. I would like to add a checkbox to each top level item to the left of the name (first item in row). When the top item is selected/deselected, all child items should be selected/deselected. When the selection state of a child item is changed to be different from the parent item, the parent item should be changed to tristate. I have found this answer, which is for a QTreeWidget. How is this done in a QTreeView? Current code can be seen below

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class MyWidget(QWidget):
    def __init__(self):
        super(MyWidget, self).__init__()
        self.tree = QTreeView(self)
        self.tree.setAlternatingRowColors(True)

        layout = QVBoxLayout(self)
        layout.addWidget(self.tree)
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(['Name', 'Height', 'Weight'])
        self.tree.header().setDefaultSectionSize(180)
        self.tree.setModel(self.model)
        self.populate_tree()
        self.tree.expandAll()

    def populate_tree(self):
        self.model.setRowCount(0)
        root = self.model.invisibleRootItem()
        class1 = QStandardItem('Class 1')
        class1.setFlags(class1.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) #Doesn't work
        class2 = QStandardItem('Class 2')
        class1.setFlags(class2.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
        root.appendRow(class1)
        root.appendRow(class2)

        class1.appendRow([
            QStandardItem('Joe'),
            QStandardItem('178'),
            QStandardItem('76')
        ])
        class1.appendRow([
            QStandardItem('Judith'),
            QStandardItem('165'),
            QStandardItem('55')
        ])
        class2.appendRow([
            QStandardItem('Tobias'),
            QStandardItem('180'),
            QStandardItem('95')
        ])
    
if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = MyWidget()
    view.setGeometry(300, 100, 600, 300)
    view.setWindowTitle('QTreeview Example')
    view.show()
    sys.exit(app.exec_())
mr_js
  • 949
  • 12
  • 29

0 Answers0