【问题标题】:Filtering files of specific folder using QFileSystemModel and QSortFilterProxyModel subclass使用 QFileSystemModel 和 QSortFilterProxyModel 子类过滤特定文件夹的文件
【发布时间】:2017-06-08 14:52:22
【问题描述】:

我正在尝试使用 QSortFilterProxyModel 过滤 QFileSystemModel 的文件。问题是,我只想在过滤时显示特定文件夹的内容。通常,如果我只想使用 QFileSystemModel 显示特定文件夹的内容,我会这样做:

view = new QTreeView(this);
fSystemModel = new QFileSystemModel(this);

view->setModel(fSystemModel);

fSystemModel->setRootPath("C:/Qt");
QModelIndex idx = fSystemModel->index("C:/Qt");

view->setRootIndex(idx);

但是当我使用 QSortFilterProxyModel 时,索引必须是 QSortFilterProxyModel 的。由于我在Qt Documentation 中找不到关于这个问题的太多信息,所以我环顾四周,找到了this thread。以此为基础,我创建了以下内容:

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    layout = new QVBoxLayout();
    ui->centralWidget->setLayout(layout);

    view = new QTreeView(this);
    fSystemModel = new QFileSystemModel(this);
    filter = new FilterModel();

    filter->setSourceModel(fSystemModel);

    layout->addWidget(view);
    view->setModel(filter);

    fSystemModel->setRootPath("C:/Qt");
    QModelIndex idx = fSystemModel->index("C:/Qt");
    QModelIndex filterIdx = filter->mapFromSource(idx);

    qDebug() << filterIdx.isValid();

    view->setRootIndex(filterIdx);
}

FilterModel.cpp(QSortFilterProxyModel 子类)

#include "filtermodel.h"

bool FilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    QModelIndex zIndex = sourceModel()->index(source_row, 0, source_parent);
    QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel());
    return fileModel->fileName(zIndex).contains("C"); //This line will have custom 
                                                      //filtering behaviour in the future, 
                                                      //instead of the name searching one.
}

但是,当我运行程序时,它没有使用指定的根索引。此外,当我使用 qDebug() 来查看 filterIdx 是否有效时,它会打印错误。我做错了什么?

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    试试看下一行的结果

    qDebug() << idx << " " << fSystemModel->fileName(idx) << " " << filterIdx.isValid();
    

    您会注意到fSystemModel-&gt;fileName(idx)"Qt"(不是完整路径"C:/Qt")。所以它不包含来自您的过滤器的"C" (FilterModel::filterAcceptsRow)。

    【讨论】:

    • 我不明白这如何解释我的问题,因为如果我使用 qDebug() filePath(idx) ,显示完整路径。你能再澄清一点吗?
    • 好的,再次查看我的代码后,我明白你的意思了。不过,如果我使用 return fileModel->filePath(zIndex).contains("C");,它只会移动到指定的文件夹。我如何从那里过滤?显然,使用 &&|| 将我的过滤器与另一个过滤器组合将不起作用,因为过滤器作为一个整体应用于文件路径。是否有解决方法,或者我应该尝试不同的方法?
    • 例如fileModel-&gt;filePath(zIndex) == "C:/Qt" || fileModel-&gt;fileName(zIndex).contains("o");我写"o"是因为Qt文件夹没有包含"C"的文件:)
    • 这正是我所缺少的!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多