|
| 1 | +import os |
| 2 | +import sys |
| 3 | + |
| 4 | +from PySide6.QtCore import QDir, QModelIndex |
| 5 | +from PySide6.QtGui import QStandardItem, QStandardItemModel |
| 6 | +from PySide6.QtWidgets import ( |
| 7 | + QApplication, |
| 8 | + QFileSystemModel, |
| 9 | + QHBoxLayout, |
| 10 | + QTreeView, |
| 11 | + QWidget, |
| 12 | +) |
| 13 | + |
| 14 | + |
| 15 | +class MainWidget(QWidget): |
| 16 | + def __init__(self, parent=None): |
| 17 | + super().__init__(parent) |
| 18 | + self.setWindowTitle("文件浏览器") |
| 19 | + |
| 20 | + # 文件系统模型,只显示文件夹 |
| 21 | + self._file_model = QFileSystemModel() |
| 22 | + self._file_model.setFilter(QDir.Dirs | QDir.NoDotAndDotDot) # type: ignore |
| 23 | + self._file_model.setRootPath("") |
| 24 | + |
| 25 | + # 创建目录树视图 |
| 26 | + self._tree_view = QTreeView(self) |
| 27 | + self._tree_view.setModel(self._file_model) |
| 28 | + self._tree_view.setHeaderHidden(True) |
| 29 | + |
| 30 | + # 隐藏:文件大小、类型、修改时间 |
| 31 | + for col in range(1, 4): |
| 32 | + self._tree_view.setColumnHidden(col, True) |
| 33 | + |
| 34 | + # 设置双击为展开文件到列表 |
| 35 | + self._tree_view.doubleClicked.connect(self.flush_filelist) |
| 36 | + |
| 37 | + # 文件列表模型 |
| 38 | + self._filelist_model = QStandardItemModel() |
| 39 | + |
| 40 | + # 创建文件列表视图 |
| 41 | + self._filelist_view = QTreeView(self) |
| 42 | + self._filelist_view.setModel(self._filelist_model) |
| 43 | + self._filelist_view.setEditTriggers(QTreeView.NoEditTriggers) |
| 44 | + |
| 45 | + # 添加布局 |
| 46 | + layout = QHBoxLayout() |
| 47 | + layout.addWidget(self._tree_view) |
| 48 | + layout.addWidget(self._filelist_view) |
| 49 | + self.setLayout(layout) |
| 50 | + |
| 51 | + def flush_filelist(self, index: QModelIndex): |
| 52 | + """刷新文件列表""" |
| 53 | + self._filelist_model.clear() |
| 54 | + path = self._file_model.filePath(index) |
| 55 | + # 设置列表头 |
| 56 | + self._filelist_model.setHorizontalHeaderLabels([path]) |
| 57 | + |
| 58 | + # 遍历文件夹下的文件 |
| 59 | + for file in os.listdir(path): |
| 60 | + if os.path.isfile(os.path.join(path, file)): |
| 61 | + item = QStandardItem(file) |
| 62 | + self._filelist_model.appendRow(item) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + app = QApplication(sys.argv) |
| 67 | + window = MainWidget() |
| 68 | + window.resize(600, 400) |
| 69 | + window.show() |
| 70 | + sys.exit(app.exec()) |
0 commit comments