PyQt QTreeWidget

Summary: in this tutorial, you’ll learn how to use the PyQt QTreeWidget class to create a tree widget that displays hierarchical data.

Introduction to the PyQt QTreeWidget class

The QTreeWidget class allows you to create a tree view widget that consists of items. The items of the tree have parent/child relationships. The QTreeWidgetItem class represents the item of the tree.

To create a tree widget, you follow these steps:

First, create a QTreeWidget object:

tree = QTreeWidget(parent)Code language: Python (python)

The parent argument is the parent widget or the main window.

Second, set the number of columns for the tree using the setColumnCount() method:

tree.setColumnCount(column_count)Code language: Python (python)

Third, set the header labels for the columns of the tree widget using the setHeaderLabels() method:

tree.setHeaderLabels(headers)Code language: Python (python)

Fourth, create a new QTreeWidgetItem object and set the item text:

item = QTreeWidgetItem(tree)
item.setText(column_index, item_text)Code language: Python (python)

The first argument of the setText() method is the column index starting from zero and the second argument is item text.

Optionally, you can set the icon for the tree item:

item.setIcon(column_index, QIcon(icon_path))Code language: Python (python)

To add an item as a child of another item, you use the addChild() method of the QTreeWidgetItem class:

item.addChild(child_item)Code language: Python (python)

PyQt QTreeWidget example

We’ll develop a simple program that displays the departments and employees of the departments using the QTreeWidget.

Here’s the program:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QTreeWidget, QTreeWidgetItem
from PyQt6.QtCore import Qt,QSize
from PyQt6.QtGui import QIcon, QAction


class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('PyQt QTreeWidget')
        self.setGeometry(100, 100, 400, 200)

        # tree
        tree = QTreeWidget(self)
        tree.setColumnCount(2)
        tree.setHeaderLabels(['Departments', 'Employees'])

        departments = ['Sales','Marketing','HR']
        employees = {
            'Sales': ['John','Jane','Peter'],
            'Marketing': ['Alice','Bob'],
            'HR': ['David'],
        }

        # addition data to the tree
        for department in departments:
            department_item = QTreeWidgetItem(tree)
            department_item.setText(0,department)
            # set the child
            for employee in employees[department]:
                employee_item   = QTreeWidgetItem(tree)
                employee_item.setText(1,employee)

                department_item.addChild(employee_item)

        # place the tree on the main window
        self.setCentralWidget(tree)

    

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())Code language: Python (python)

How it works.

First, create a new QTreeWidget, configure its column acount, and set the header labels:

 tree = QTreeWidget(self)
 tree.setColumnCount(2)
 tree.setHeaderLabels(['Departments', 'Employees'])Code language: Python (python)

Second, prepare data for display on the tree widget:

departments = ['Sales','Marketing','HR']
employees = {
    'Sales': ['John','Jane','Peter'],
    'Marketing': ['Alice','Bob'],
    'HR': ['David'],
}Code language: Python (python)

Third, add the departments to the first column of the tree. For each department, add the employees to the second column and as the children items of the department:

for department in departments:
    department_item = QTreeWidgetItem(tree)
    department_item.setText(0,department)
    # set the children
    for employee in employees[department]:
        employee_item   = QTreeWidgetItem(tree)
        employee_item.setText(1,employee)
        department_item.addChild(employee_item)Code language: Python (python)

Finally, place the tree widget as the central widget of the main window:

self.setCentralWidget(tree)Code language: Python (python)

Summary

  • Use the QTreeWidget class to create a tree widget.
  • Use the setColumnCount() method of the QTreeWidget class to set the columns for the tree.
  • Use the setHeaderLabels() method of the QTreeWidget class to set the column headers of the tree.
  • Use the QTreeWidgetItem class to create a tree widget item.
  • Use the addChild() method of the QTreeWidgetItem to establish the parent/child relationship between items.
Did you find this tutorial helpful ?