PySide6 QTreeView Example

QTreeView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# The QTreeView class provides an  
# implementation of a tree view.
# For the model we are using QFileSystemModel
# provided by Qt so no need for subclassing.

import sys

from PySide6.QtCore import QDir
from PySide6.QtWidgets import QFileSystemModel
from PySide6.QtWidgets import (QApplication,
    QWidget, QVBoxLayout, QTreeView)


class Window(QWidget):
    
    def __init__(self):

        super().__init__()
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 1 - Create the tree view
        
        tree_view = QTreeView()
        
        # 2 - Create the model and set its root path 
        #     to the user's home directory.
        
        model = QFileSystemModel()
        model.setRootPath(QDir.home().path())
        
        # 3 - Set the tree view's model
        
        tree_view.setModel(model)
        
        # 4 - This line sets the tree view root index,
        #     to the index of the user's home directory. 
        #     Any changes to files and directories within root
        #     will be reflected in the model.
        
        tree_view.setRootIndex(model.index(QDir.home().path()))
        
        layout.addWidget(tree_view)
        
        # It's a start of a rudimentary file manager
        # in a few lines of code!


if __name__ == '__main__':

    app = QApplication(sys.argv)

    main_window = Window()
    main_window.show()

    sys.exit(app.exec())

Just as QTableView is QTableWidget’s parent, QTreeView1 is the parent class of QTreeWidget designed to display tree-like data structures. To use QTreeView in your application

  1. Create a QTreeView instance.

  2. Create a model object. In the example we use QFileSystemModel a ready-made subclass of QAbstractItemModel provided by Qt that models the file system hierarchy. If you need to display your own custom tree-like data structures you need to create a QAbstractItemModel subclass yourself, implementing the required methods. Also set the model’s root path to the current user’s home directory.

  3. Set the treeview’s model using QTreeView.setModel().

  4. Set the QTreeView root index to the index of the current user’s home directory.

QFileSystemModel will pick up any changes to to file system tree and update the view automatically.