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())
|