Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ QTreeView、QFileSystemModel、setRootPath和QSortFilterProxyModel以及用于过滤的RegExp_C++_Qt - Fatal编程技术网

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

C++ QTreeView、QFileSystemModel、setRootPath和QSortFilterProxyModel以及用于过滤的RegExp,c++,qt,C++,Qt,我需要显示一个特定目录的QTreeView,我想让用户能够使用RegExp过滤文件 根据我对Qt文档的理解,我可以通过标题中提到的类实现这一点,如下所示: // Create the Models QFileSystemModel *fileSystemModel = new QFileSystemModel(this); QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this); // Set the Root P

我需要显示一个特定目录的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行编辑中的所有文本(或输入类似“.”的RegExp)后,它将再次显示所有目录(在Windows上,这意味着所有驱动器等)


我做错了什么/

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

我认为正在发生的事情,是这样吗 一旦您开始过滤,系统将 作为根目录使用的索引没有 不再存在。然后,视图将重置为 作为根索引的索引无效。 过滤基本上起作用 模型树,而不仅仅是你 看看你是否开始输入你的过滤器

我想你需要一个 修改了代理模型以执行您需要的操作 希望它应该只适用于 筛选根目录下的项目 路径,但让根路径本身 (以及其他一切)独自一人


因此,在子类化QSortFilterProxyModel并检查函数filterAcceptsRow()中的一些父()之后,现在确实可以按预期工作了

我通过谷歌找到了这条线索,并根据这条线索(以及其他谷歌搜索结果)制定了一个解决方案。您可以在以下位置找到我的解决方案:

您必须记住的一件事(这里没有提到)是QFileSystemModel不会自动获取子行,因此您必须对它们调用fetchMore()。在我的例子中,我们只有一级子目录,所以这相当容易


如果您的代码想要处理更多不同的目录层次结构,您需要将filterAcceptsRow()底部附近的for()循环更改为递归循环。

您是否有机会分享您所做的修改?我现在遇到了这个问题,但不知道如何解决。遗憾的是,我再也无法访问这个项目了。这是邮件列表线程: