maurobio
maurobio

Reputation: 1577

python - Synchronizing two QTreeWidgets

I have two QTreeWidget's in a form, one without children, the other with children as depicted in the screenshot below. I want that the right tree be expanded if it is collapsed (and collapsed if it is expanded), each time an item in the left tree is selected.

enter image description here

I tried to achieve this with the code below, where I connect a handle function to the itemSelectionChanged event of the left list. The problem is that the .collapse() and .expand() methods require a QIndexModel parameter (inherited from QTreeView), but QTreeWidget use a predefined model which I don't know how to access.

Can anyone out there give me hand?

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.tree1 = QtGui.QTreeWidget(self)
        self.tree2 = QtGui.QTreeWidget(self)
        layout = QtGui.QHBoxLayout(self)

        self.tree1.header().hide()
        self.tree2.header().hide()
        self.tree1.itemSelectionChanged.connect(self.handleSelected)
        for text in 'A B C D'.split():
            item = QtGui.QTreeWidgetItem(self.tree1, [text])
        for text in '1 2 3 4'.split():
            item = QtGui.QTreeWidgetItem(self.tree2, [text])
            for text in 'red blue green'.split():
                child = QtGui.QTreeWidgetItem(item, [text])
        layout.addWidget(self.tree1)
        layout.addWidget(self.tree2)

    def handleSelected(self):
        if self.tree2.isExpanded():
            self.tree2.collapse()
        else:
            self.tree2.expand()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

Upvotes: 1

Views: 171

Answers (1)

ekhumoro
ekhumoro

Reputation: 120578

The tree-widget items have a setExpanded method and an isSelected method, so all you need to do is iterate over the top-level items and toggle each one:

def handleSelected(self):
    for index in range(self.tree1.topLevelItemCount()):
        item1 = self.tree1.topLevelItem(index)
        item2 = self.tree2.topLevelItem(index)
        item2.setExpanded(item1.isSelected())

Upvotes: 1

Related Questions