简体   繁体   中英

List files in sub-directories with QDir's filter

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.

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"

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.

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