简体   繁体   中英

Filtering only dirs and xml file in QFileSystemModel in Qt

i have implemented a custom file browing dialog with the help of

QListView
QTreeView
QFileSystemModel

What i want !

a browsing dialog which use to browse xml file only. So i want to show dirs and xml files only in QListView

if a dir has xml file then xml file will list under that dir

otherwise just display dir as empty ( no matter how many it holds except xml )

like in most of cases where you are browsing a specific type of file. as in MSWord ( show only .doc and .docx to browse)

What i have done

m_ptrModelForTree  = new QFileSystemModel(this);
m_ptrModelForTree->setFilter(QDir::Dirs | QDir::NoDotAndDotDot);
m_ptrModelForTree->setRootPath("");
ui->treeView->setModel(m_ptrModelForTree);
ui->treeView->hideColumn(1);
ui->treeView->hideColumn(2);
ui->treeView->hideColumn(3);
ui->treeView->header()->hide();

m_ptrModelForList = new QFileSystemModel(this);
m_ptrModelForList->setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
m_ptrModelForList->setRootPath("");
ui->listView->setModel(m_ptrModelForList);
ui->listView->setRootIndex(m_ptrModelForList->index("c:\\"));

What i got

dialog which showing all dirs and all file ( but i need only xml file to display )

What i tried

m_ptrModelForList->setNameFilters(QStringList()<<".xml");

but it showing xml file only, not dirs.

please give me suggestion what to do.

Actually it's a solution suggested by @Andreas in comments to the question. My contribution is pointing to another mistake in the name filter.

Solution : how to show all dirs + files filtered by extension

  1. Use flag QDir::AllDirs. According to docs this flag is intented to avoid applying the filter to folders.

    setFilter(QDir::Files | QDir::AllDirs | QDir::NoDotAndDotDot);

  2. Use setNameFilters to set a filter for files. The filters are wildcards .
    Your mistake that use set it to ".xml" which means that a file shouldn't have its name but extension only to match your filter. The right filter is:

    setNameFilters(QStringList() << "*.xml")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM