Search code examples
c++qtqfilesystemmodel

Displaying just the files with correct extension


I'm trying in QFileSystemModel display just files with extention *.txt and the other types shaded/grayed out:

  • proxy_ is of type QSortFilterProxyModel

  • model_ is of type QFileSystemModel

Here's my code:

proxy_->setFilterWildcard("*.txt");  
proxy_->setSourceModel(model_);
model_->setNameFilters(QStringList(proxy_->filterRegExp().pattern()));
model_->setNameFilterDisables(true);
sel_model_ = (new QItemSelectionModel(proxy_));
treeView->setModel(proxy_);
treeView->setSelectionModel(sel_model_);

...but by doing so nothing is shown in my view. Anyone knows what I'm doing wrong?


Solution

  • You can set a file name filter with QFileSystemModel::setNameFilters.

    In the example program below .txt and folders are displayed normally, and other files are disabled (greyed out).

    The nameFilterDisables property allows you to choose between filtered out files being disabled or hidden.

    #include <QtGui>
    
    int main(int argc, char** argv)
    {
        QApplication app(argc, argv);
    
        QFileSystemModel model;
        model.setRootPath(QDir::rootPath());
    
        QStringList filters;
        filters << "*.txt";
    
        model.setNameFilters(filters);
    
        QTreeView view;
        view.setModel(&model);
        view.show();
    
        return app.exec();
    }