我需要显示特定目录的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)));
Run Code Online (Sandbox Code Playgroud)
启动程序时,TreeView正确地固定到指定的目录.但是一旦用户更改了RegExp,看起来TreeView就会忘记它的RootIndex.删除RegExp LineEdit中的所有文本(或输入类似"."的RegExp)后,它再次显示所有目录(在Windows上,这意味着所有驱动器等)
我究竟做错了什么?:/
我收到了Qt邮件列表的回复,解释了这个问题:
我认为正在发生的是,只要您开始过滤,您用作根的索引就不再存在.然后,视图将重置为无效索引作为根索引.过滤适用于整个模型树,而不仅仅是您开始输入过滤器时看到的部分!
我认为你需要一个修改过的代理模型来做你想做的事情.它应该只对您的根路径下的项目应用过滤,但只让根路径本身(以及其他所有内容).
因此,在对函数filterAcceptsRow()进行子类化QSortFilterProxyModel和一些parent()检查之后,这确实可以正常工作!
| 归档时间: |
|
| 查看次数: |
4842 次 |
| 最近记录: |