gpt4 book ai didi

c++ - QTreeView、QFileSystemModel、setRootPath 和 QSortFilterProxyModel 以及用于过滤的 RegExp

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:11 26 4
gpt4 key购买 nike

我需要显示特定目录的 QTreeView,我想让用户可以使用 RegExp 过滤文件。

据我了解 Qt 文档,我可以使用标题中提到的类来实现这一点:

// Create the Models
QFileSystemModel *fileSystemModel = new QFileSystemModel(this);
QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);

// Set the Root Path
QModelIndex rootModelIndex = fileSystemModel->setRootPath("E:\\example");

// Assign the Model to the Proxy and the Proxy to the View
proxyModel->setSourceModel(fileSystemModel);
ui->fileSystemView->setModel(proxyModel);

// Fix the TreeView on the Root Path of the Model
ui->fileSystemView->setRootIndex(proxyModel->mapFromSource(rootModelIndex));

// Set the RegExp when the user enters it
connect(ui->nameFilterLineEdit, SIGNAL(textChanged(QString)),
proxyModel, SLOT(setFilterRegExp(QString)));

启动程序时,TreeView 会正确固定到指定目录。但是一旦用户更改了 RegExp,TreeView 似乎就忘记了它的 RootIndex。删除 RegExp LineEdit 中的所有文本(或输入类似“.”的 RegExp)后,它再次显示所有目录(在 Windows 上这意味着所有驱动器等)

我做错了什么? :/

最佳答案

我收到了 Qt 邮件列表的回复,其中解释了这个问题:

What I think is happening, is that as soon as you start filtering, the index you use as your root does no longer exist. The view then resets to an invalid index as the root index. The filtering works on the whole model tree, not just on the part you see if you start to enter your filter!

I think you are going to need a modified proxy model to do what you want. It should only apply the filtering on items under your root path, but let the root path itself (and everything else) alone.

所以在子类化 QSortFilterProxyModel 和一些 parent() 函数 filterAcceptsRow() 检查之后,这现在确实按预期工作了!

关于c++ - QTreeView、QFileSystemModel、setRootPath 和 QSortFilterProxyModel 以及用于过滤的 RegExp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3212392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com