one type of file format in QTreeView

2019-07-20 14:10发布

问题:

Is it possible to set only one file format visible to the user? I'm searching it in documentation, but I can't find it... If not, which other widget you are suggesting to use?

回答1:

I assume you're using a QTreeView with a QFileSystemModel. If not, I'd suggest doing so. QTreeWidget is not as flexible.

QFileSystemModel has a method called setNameFilters that should do what you want. To use it, do something like this:

QStringList filters;
filters.append("*.cc"); // whatever filters you want
filters.append("*.h");

QFileSystemModel *model = new QFileSystemModel;
model->setNameFilters(filters);

QTreeView *view = new QTreeView;
view->setModel(model);


回答2:

//filter treeview for directories and torrent files only

QStringList filters;
filters << "*.torrent";

QDirModel model = new QDirModel(this);
model->setReadOnly(true);
model->setSorting(QDir::DirsFirst |QDir::IgnoreCase | QDir::Type);
model->setFilter(QDir::AllDirs | QDir::AllEntries |QDir::NoDotAndDotDot);

model->setNameFilters(filters);
ui->treeView->setModel(model);