我需要显示特定目录的 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。删除正则表达式行编辑中的所有文本(或输入“.”等正则表达式)后,它会再次显示所有目录(在 Windows 上,这意味着所有驱动器等)
我究竟做错了什么? :/
我从 Qt 邮件列表中收到了回复,其中解释了这个问题:
我认为正在发生的事情是
一旦您开始过滤,
您作为根使用的索引不会
不再存在。然后视图重置为
作为根索引的索引无效。
过滤总体有效
模型树,不仅仅是你的部分
看看你是否开始进入你的过滤器!
我想你需要一个
修改代理模型来做你想做的事
想。它应该只应用
过滤根目录下的项目
路径,但让根路径本身
(以及其他一切)独自一人。
因此,在对 QSortFilterProxyModel 进行子类化并在函数 filterAcceptsRow() 中进行一些parent()检查之后,现在它确实按预期工作了!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)