簡體   English   中英

使用QFileSystemModel和QSortFilterProxyModel子類過濾特定文件夾的文件

[英]Filtering files of specific folder using QFileSystemModel and QSortFilterProxyModel subclass

我正在嘗試使用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文檔中找不到有關此問題的大量信息,因此我環顧四周並找到了該線程 我以此為基礎,創建了以下內容:

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是否有效時,它會輸出false。 我究竟做錯了什么?

嘗試查看下一行的結果

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

您會注意到fSystemModel->fileName(idx)"Qt" (不是完整路徑"C:/Qt" )。 因此它不包含過濾器中的"C"FilterModel::filterAcceptsRow )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM