1

I've used in the past the Qt.ItemIsTristate flag with a QTreeWidget to automatically select children when an item is selected by the user.

Here is an example with QTreeWidget :

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        self.tree = QtGui.QTreeWidget()

        for k in range(0, 4):
            parent = self.tree

            for i in range(0, 4):
                item = QtGui.QTreeWidgetItem(parent)
                item.setText(0, "item %d %d" % (k, i) )
                item.setFlags(item.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
                item.setCheckState(0, Qt.Unchecked)

                parent = item

        self.tree.expandToDepth(4)

        self.setCentralWidget(self.tree)
        self.resize(200, 300)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

With this code, when an item is checked, all its children are also checked.

Now, I need to do the same thing but with QTreeView. I've tested the following code :

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        self.model = QtGui.QStandardItemModel()

        for k in range(0, 4):
            parentItem = self.model.invisibleRootItem()
            for i in range(0, 4):
                item = QtGui.QStandardItem("item %d %d" % (k,i) )
                item.setFlags(item.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable)
                item.setCheckState( Qt.Unchecked)

                parentItem.appendRow(item)
                parentItem = item

        self.view = QtGui.QTreeView()
        self.view.setModel(self.model)
        self.view.expandToDepth(4)

        self.setCentralWidget(self.view)
        self.resize(200, 300)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

With this code, when an item is checked, its children are not checked.

Have you any hint to setup the QTreeView/QStandardItem version to work as in the first example ?

I'm using PyQt4 4.11.

Best regards, Elby

Elby
  • 11
  • 2

1 Answers1

0

To select all the children of a particular model index you need to do the following.

1) enable multiple selections self.view.SetSelectionMode(QAbstractItemView::MultiSelection)

2) Traverse along the tree using 'rowcount' and 'index' methods

3) use selection model to perform selections on model index self.view.SelectionModel().select(qmodelindex,QItemSelectionModel.Select)

P.S : I work on c++ api, so there might be error in the case and syntax