Jacobus
Jacobus

Reputation: 119

Get the place in one Qtreewidget and expand another to the same place

I have two QTreeWidgets in my QT app, using python (PyQt4).

I want to

Manually expand TreeWidget 1 to an item and then. If this item is in TreeWidget 2, make TreeWidget 2 expand to the same item.

The reason is I have 2 tabs each have a treewidget.

You will need to excuse me, I'm not an experienced programmer and have been struggling.

Thanks

Upvotes: 1

Views: 2041

Answers (1)

ekhumoro
ekhumoro

Reputation: 120588

The question is a little light on details, since it doesn't specify what counts as the "same" item, and doesn't state which items can be expanded.

However, this simple demo script should provide a reasonable starting point:

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)
        for tree in (self.tree1, self.tree2):
            tree.header().hide()
            tree.itemExpanded.connect(self.handleExpanded)
            tree.itemCollapsed.connect(self.handleCollapsed)
            for text in 'one two three four'.split():
                item = QtGui.QTreeWidgetItem(tree, [text])
                for text in 'red blue green'.split():
                    child = QtGui.QTreeWidgetItem(item, [text])
            layout.addWidget(tree)

    def handleExpanded(self, item):
        self.syncExpansion(item, True)

    def handleCollapsed(self, item):
        self.syncExpansion(item, False)

    def syncExpansion(self, item, expand=True):
        if item is not None:
            tree = item.treeWidget()
            if tree is self.tree1:
                tree = self.tree2
            else:
                tree = self.tree1
            text = item.text(0)
            for other in tree.findItems(text, QtCore.Qt.MatchFixedString):
                other.setExpanded(expand)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(300, 500, 300, 300)
    window.show()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions