我有一个应用程序,需要显示两个不同的TreeViews。一个用于显示文件夹( folderView ),另一个将显示来自folderView的选定文件夹中的文件(fileView)。下面的代码运行良好,但我有一个奇怪的问题:例如,在下面的屏幕快照中,如果我单击bin文件夹,然后切换回VBoxGuestAdd.,fileView将在fileView中显示bin文件夹。p.s.:使用ubuntu 22.04机器

在这里,我的代码:
import sys
from PySide6.QtCore import QDir
from PySide6.QtWidgets import QApplication, QWidget, QHBoxLayout, QTreeView, QFileSystemModel
def folderView_selectionchanged():
current_index = folderView.currentIndex()
selected_folder_path = folderModel.fileInfo(current_index).absoluteFilePath()
fileView.setRootIndex(fileModel.setRootPath(selected_folder_path))
app = QApplication(sys.argv)
window = QWidget()
layout = QHBoxLayout()
folderView = QTreeView()
folderModel = QFileSystemModel()
folderModel.setRootPath("/")
folderModel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)
folderView.setModel(folderModel)
folderView.selectionModel().selectionChanged.connect(folderView_selectionchanged)
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()发布于 2022-11-10 16:14:40
这是一个"bug“,可能是由QFileSystemModel的异步特性引起的,它使用线程来填充模型,并延迟对模型结构更新的调用。
它似乎也已经被报道为QTBUG-93634,但还没有得到关注。
一个可能的解决办法是“重置”过滤器并再次设置它:
def folderView_selectionchanged():
current_index = folderView.currentIndex()
selected_folder_path = folderModel.fileInfo(current_index).absoluteFilePath()
fileView.setRootIndex(fileModel.setRootPath(selected_folder_path))
fileModel.setFilter(QDir.AllDirs)
fileModel.setFilter(QDir.NoDotAndDotDot | QDir.Files)但是,以上可能不适用于大/慢的文件系统。我能想到的唯一可能的解决方案是使用QSortFilterProxyModel并覆盖filterAcceptsRow()函数。它不会像基本模型那么快,但它会像预期的那样工作。
请注意:
filterAcceptsRow()总是根据模型层次结构进行检查,所以总是允许过滤器传递过滤目录之外的任何内容是强制性的,否则它将被过滤掉(如果父目录被过滤掉,就没有子目录显示);setRootPath()使布局无效并再次检查筛选器,我们必须清除验证,直到设置了新的根路径,然后恢复它并重新设置筛选器;这是通过将实际的过滤函数临时替换为一个始终返回True的虚拟筛选函数来完成的;class FileProxy(QSortFilterProxyModel):
validParent = None
def __init__(self):
super().__init__()
self.fsModel = QFileSystemModel()
self.setSourceModel(self.fsModel)
def filterAcceptsRow(self, row, parent):
return (
self.validParent != parent
or not self.fsModel.isDir(
self.fsModel.index(row, 0, parent))
)
def setRootPath(self, path):
func = self.filterAcceptsRow
self.filterAcceptsRow = lambda *args: True
self.validParent = self.fsModel.setRootPath(path)
self.filterAcceptsRow = func
self.invalidateFilter()
return self.mapFromSource(self.validParent)https://stackoverflow.com/questions/74391441
复制相似问题