You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySide6中QTreeView文件视图异常显示文件夹的技术问题

解决QTreeView切换文件夹时文件视图显示异常的问题

问题原因

你的代码核心问题在于两点:

  1. 使用了selectionChanged信号,该信号会在选区变化时多次触发(比如多选操作),容易导致重复执行路径切换逻辑,引发异步加载冲突;
  2. 直接依赖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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:01:12