SASUPERNOVA
SASUPERNOVA

Reputation: 141

Filtering files of specific folder using QFileSystemModel and QSortFilterProxyModel subclass

I am trying to filter files of QFileSystemModel using QSortFilterProxyModel. The problem is, I want to only show the contents of a specific folder while filtering. Normally, if I wanted to only show the contents of a specific folder using QFileSystemModel, I would do something like this:

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

view->setModel(fSystemModel);

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

view->setRootIndex(idx);

But when I use the QSortFilterProxyModel, the index has to be the QSortFilterProxyModel's. Since I could not find much information in Qt Documentation regarding this issue, I looked around and found this thread. Using this as a base, I created the following:

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 subclass)

#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.
}

However, when I run the program, it does not use the specified root index. Moreover, when I use qDebug() to see if the filterIdx is valid, it prints false. What am I doing wrong?

Upvotes: 0

Views: 970

Answers (1)

olya
olya

Reputation: 312

Try to see the result of the next line

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

You can notice that fSystemModel->fileName(idx) is "Qt" (not full path "C:/Qt"). So it doesn't contain "C" from your filter (FilterModel::filterAcceptsRow).

Upvotes: 1

Related Questions