Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

qt - Filtering QFilesystemModel

I'm using a QFileSystemModel with a QListview to display all files from a directory. I'd like to filter that model to display some categories of files like :

  • textual files : *.txt *.csv *.tab
  • music : *.mp3 *.flac *.ogg
  • movies : *.avi *.mkv

My current code is :

  MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
     Filemodel = new QFileSystemModel(this)                      ;
     Filemodel->setFilter( QDir::NoDotAndDotDot | QDir::Files )  ;
     proxy_model = new QSortFilterProxyModel();

     proxy_model ->setDynamicSortFilter(true);
     proxy_model ->setSourceModel( Filemodel ); 
     proxy_model ->setFilterKeyColumn(0);
     ui->Filtered_tbView->setModel( proxy_model )                ;
}

(...)

/* combobox event to select file type to filter */
 void MainWindow::on_FSFilter_Combo_currentIndexChanged(int index)
{
 proxy_model->setFilterWildcard("*.txt");  // just a simple example here
 ui->Filtered_tbView->setModel( proxy_model )                ;
}

That code doesn't display anything while all type of files are present in the directory.

Besides, things I've tried that wasn't fine for me (pointers may be useful for further readers) :

  • setNameFilters : work well but lets show all files (unfiltered are just greyed)
  • the Custom Sort/Filter Model Example -> while using QSortFilterProxyModel this example is somewhat too complicated to just filter out the file extentions, besides it uses regexp that is not the best method when using many filters like here.
  • I've also found an interesting snippet from qt-project but couldn't found out how to implement it for rows with multiple extensions
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest way is to use QFileSystemModel::setNameFilters.

With the property QFileSystemModel::nameFilterDisables you can choose between filtered out files being disabled or hidden.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    Filemodel = new QFileSystemModel(this)                      ;
    Filemodel->setFilter( QDir::NoDotAndDotDot | QDir::Files )  ;

    QStringList filters;
    filters << "*.txt";

    Filemodel.setNameFilters(filters);
    Filemodel.setNameFilterDisables(false);

    ui->Filtered_tbView->setModel( Filemodel )                  ;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...