List files in sub-directories with QDir's filter

7.1k views Asked by At

I'm looking for a function similar to the python glob function.

If my folder structure is:
folder1/abc1.txt
folder1/xyz1.txt
folder1/abc2.txt
folder2/abc3.txt
folder2/xyz4.txt
folder3/abc5.txt

then if I give */abc*, I'm looking for an output of:

folder1/abc1.txt
folder1/abc2.txt
folder2/abc3.txt
folder3/abc5.txt

I tried entrylist, but it just lets me filter on what's in the current folder.

2

There are 2 answers

2
László Papp On BEST ANSWER

You can of course traverse recursively with an embedded loop like this:

main.cpp

#include <QDir>
#include <QFileInfoList>
#include <QString>
#include <QStringList>
#include <QDebug>

void traverse(const QString &pattern, const QString &dirname, int level)
{
    QDir dir(dirname);
    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::NoDot | QDir::NoDotDot);

    static const QStringList stringList = pattern.split('/');
    foreach (QFileInfo fileInfo, dir.entryInfoList(stringList.mid(level, 1))) {
        if (fileInfo.isDir() && fileInfo.isReadable())
            traverse(pattern, fileInfo.filePath(), level+1);
        else if (stringList.size() == (level + 1))
            qDebug() << fileInfo.filePath();
    }
}

int main()
{
    traverse("*/abc*", ".", 0);
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

"./folder1/abc1.txt"
"./folder1/abc2.txt"
"./folder2/abc3.txt"
"./folder3/abc5.txt"
0
ΦXocę 웃 Пepeúpa ツ On

for those using the new version of QT

my suggestion would be, use the [qdirEntryList][1]:

  1. set the root to root_directory
  2. then search all the images using a filter(png, jpj or what you need) and
  3. then generate a pseudo random number between 0 and list.size() and
  4. use that as index for getting the path of the image,
  5. that finally you will use in the constructor of the QImage Object you are going to return.