[Tips]How to Execute Function When Tab Opens in QTreeWidget

GOAL

Today’s goal is to implement PySide Widget where a function is executed when the tab is expanded. For example, the following is a function to print opened item name.

Environment

Windows 10
Python 3.8.7
PySide2 (5.15.2)

Method

Use itemExpanded

Connect target function to itemExpanded signal of QTreeWidget.

tree_widget = QTreeWidget()
tree_widget.itemExpanded.connect(self._display_opened_item)

def _display_opened_item(self, item):
    print("Opened item is " + item.text(0))

The completed code

The completed code will be as follows.

import sys
from PySide2.QtWidgets import *
from PySide2.QtCore import Qt


class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self._generate_ui()
        self._init_tree_widget()

    def _generate_ui(self):
        main_widget = QWidget()
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        self.tree_widget = QTreeWidget()
        self.tree_widget.itemExpanded.connect(self._display_opened_item) #connect function here
        main_layout.addWidget(self.tree_widget)

    def _init_tree_widget(self):
        self.tree_widget.setHeaderLabels(["header"])
        tree_widget_item1 = QTreeWidgetItem(["group1"])
        tree_widget_item1.addChild(QTreeWidgetItem(["item1_1"]))
        self.tree_widget.addTopLevelItem(tree_widget_item1)
        tree_widget_item2 = QTreeWidgetItem(["group2"])
        self.tree_widget.addTopLevelItem(tree_widget_item2)
        tree_widget_item2.addChild(QTreeWidgetItem(["item2_1"]))
        tree_widget_item2.addChild(QTreeWidgetItem(["item2_2"]))

    def _display_opened_item(self, item): # the function to execute
        print("Opened item is " + item.text(0))


def launch():
    app = QApplication.instance()
    if not app:
        app = QApplication(sys.argv)
    widget = MyMainWindow()
    widget.show()
    app.exec_()


launch()

PostScript

To execute function when an item is collapsed, use itemCollapsed signal instead.