PySide6中QTreeView文件视图异常显示文件夹的技术问题
解决QTreeView切换文件夹时文件视图显示异常的问题
问题原因
你的代码核心问题在于两点:
- 使用了
selectionChanged信号,该信号会在选区变化时多次触发(比如多选操作),容易导致重复执行路径切换逻辑,引发异步加载冲突; - 直接依赖
fileModel.setRootPath()的返回值设置fileView的根索引,但QFileSystemModel是异步加载文件系统的,快速切换文件夹时,前一次的加载任务可能未完成,导致返回的索引并非目标路径的索引。
修复后的代码
import sys from PySide6.QtCore import QDir from PySide6.QtWidgets import QApplication, QWidget, QHBoxLayout, QTreeView, QFileSystemModel def folderView_current_changed(current): # 先校验选中索引是否有效 if not current.isValid(): return selected_folder_path = folderModel.filePath(current) # 直接通过路径获取fileModel中对应的索引,避免异步加载干扰 target_index = fileModel.index(selected_folder_path) fileView.setRootIndex(target_index) app = QApplication(sys.argv) window = QWidget() layout = QHBoxLayout() folderView = QTreeView() folderModel = QFileSystemModel() folderModel.setRootPath("/") folderModel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs) folderView.setModel(folderModel) # 改用currentChanged信号,仅在当前选中项变更时触发 folderView.selectionModel().currentChanged.connect(folderView_current_changed) fileView = QTreeView() fileModel = QFileSystemModel() fileModel.setRootPath("/") fileModel.setFilter(QDir.NoDotAndDotDot | QDir.Files) fileView.setModel(fileModel) layout.addWidget(folderView) layout.addWidget(fileView) window.setLayout(layout) window.show() app.exec()
关键修改说明
- 替换信号:将
selectionChanged改为currentChanged,该信号仅在当前选中的项发生变化时触发,避免不必要的重复执行; - 索引有效性校验:增加
current.isValid()判断,防止无效索引导致的路径错误; - 可靠获取目标索引:使用
fileModel.index(selected_folder_path)直接获取目标路径对应的模型索引,绕过setRootPath的异步加载返回值问题,确保fileView能准确定位到选中文件夹。
内容的提问来源于stack exchange,提问作者lebhero
相关产品推荐
相关产品推荐

