【发布时间】: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 是否有效时,它会打印错误。我做错了什么?
【问题讨论】: