PySide6 QTreeView + QStandardItemModel 树形结构

与 QTableView 相比,QTreeView 是一个树形结构的视图,用于展示层级结构的数据,使用的方式与 QTableView 相似。

前言

  • QTreeView:视图层,负责渲染树形、滚动、选中、展开折叠,本身不保存数据。
  • QStandardItemModel:标准模型,承载树的根、各级子节点,节点变化自动通知视图刷新。
  • QStandardItem:树节点,一个 Item 就是一个树节点,可以携带文本、图标、复选框、自定义数据、控制是否可编辑。

对比 QTreeWidget:QTreeWidget 是控件自带数据,适合简单快速原型;QTreeView + Model 解耦更好,后续可以替换为自定义 QAbstractItemModel,对接后端、懒加载大数据树。

QTreeView 控件介绍

从方法和信号两个方面介绍 QTreeView 控件。

方法

展开、折叠相关方法:

  • tree.expand(int):展开指定索引的节点
  • tree.collapse(int):收起指定索引的节点
  • tree.expandAll():展开所有节点
  • tree.collapseAll():收起所有节点

索引、查找相关方法:

  • tree.indexAbove(int):获取上一个节点的索引
  • tree.indexBelow(int):获取下一个节点的索引
  • tree.columnAt(int):获取指定索引的列数

信号

树结构的展开与折叠对应两个信号:

  • expanded(index):节点被展开时触发,参数是 QModelIndex
  • collapsed(index):节点被折叠时触发,参数是 QModelIndex

信号演示

 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
import sys

from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import QApplication, QLabel, QTreeView, QVBoxLayout, QWidget


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QTreeView expanded / collapsed 信号")
        self.resize(320, 300)

        model = QStandardItemModel()
        model.setHorizontalHeaderLabels(["名称"])

        fruits = QStandardItem("水果")
        fruits.appendRow(QStandardItem("苹果"))
        fruits.appendRow(QStandardItem("香蕉"))

        vegetables = QStandardItem("蔬菜")
        vegetables.appendRow(QStandardItem("白菜"))
        vegetables.appendRow(QStandardItem("萝卜"))

        model.invisibleRootItem().appendRow(fruits)
        model.invisibleRootItem().appendRow(vegetables)

        self.view = QTreeView()
        self.view.setModel(model)
        self.view.expanded.connect(self.on_expanded)
        self.view.collapsed.connect(self.on_collapsed)

        self.status = QLabel("展开或折叠节点,查看下方状态变化")

        root = QVBoxLayout(self)
        root.addWidget(self.view)
        root.addWidget(self.status)

    def on_expanded(self, index):
        self.status.setText(f"expanded:{index.data()}")

    def on_collapsed(self, index):
        self.status.setText(f"collapsed:{index.data()}")


app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec())

演示效果如下:

懒加载目录树

懒加载的交互效果:当节点展开时,根据节点的属性去加载特定的资源,基本步骤如下:

  1. 获取当前节点的索引 self.model.itemFromIndex(index)
  2. 清除节点下的所有子节点 item.removeRows(0, item.rowCount())
  3. 获取树型结构资源
  4. 循环:通过 appendRow() 方法添加子节点
 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import sys
from pathlib import Path

from PySide6.QtCore import Qt
from PySide6.QtGui import QStandardItem, QStandardItemModel
from PySide6.QtWidgets import QApplication, QLabel, QTreeView, QVBoxLayout, QWidget

PATH_ROLE = Qt.ItemDataRole.UserRole + 1
IS_DIR_ROLE = Qt.ItemDataRole.UserRole + 2
LOADED_ROLE = Qt.ItemDataRole.UserRole + 3


def create_item(path, is_dir):
    item = QStandardItem(path.name or str(path))
    item.setEditable(False)
    item.setData(str(path), PATH_ROLE)
    item.setData(is_dir, IS_DIR_ROLE)
    item.setData(False, LOADED_ROLE)

    if is_dir:
        # 占位子节点让目录项显示展开箭头;首次展开时再替换为真实内容
        placeholder = QStandardItem("加载中...")
        placeholder.setEditable(False)
        item.appendRow(placeholder)

    return item


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QTreeView 懒加载目录树")
        self.resize(500, 400)

        self.root_path = Path(__file__).resolve().parent.parent

        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(["目录"])
        self.model.invisibleRootItem().appendRow(create_item(self.root_path, True))

        self.view = QTreeView()
        self.view.setModel(self.model)
        # 目录首次展开时才加载子项
        self.view.expanded.connect(self.load_children)

        self.status = QLabel(f"根目录:{self.root_path},展开节点时加载子项")

        root = QVBoxLayout(self)
        root.addWidget(self.view)
        root.addWidget(self.status)

    def load_children(self, index):
        item = self.model.itemFromIndex(index)
        if item is None or not item.data(IS_DIR_ROLE) or item.data(LOADED_ROLE):
            return

        item.setData(True, LOADED_ROLE)
        item.removeRows(0, item.rowCount())

        path = Path(item.data(PATH_ROLE))
        try:
            children = sorted(
                path.iterdir(),
                key=lambda child: (not child.is_dir(), child.name.lower()),
            )
        except OSError as exc:
            error = QStandardItem(f"无法读取:{exc.strerror}")
            error.setEditable(False)
            item.appendRow(error)
            self.status.setText(f"读取 {path} 失败:{exc.strerror}")
            return

        count = 0
        for child in children:
            if child.is_symlink():
                continue
            is_dir = child.is_dir()
            item.appendRow(create_item(child, is_dir))
            count += 1

        self.status.setText(f"已加载 {path} 的 {count} 个子项" if count else f"{path} 是空目录")


app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec())

演示效果如下:

小结

  • QTreeView 是一个树形结构的视图,用于展示层级结构的数据
  • 介绍 QTreeView 的方法和信号,主要与展开、折叠相关
  • 给出一个懒加载目录树的示例,展示如何根据节点的属性去加载特定的资源