16

How to delete a folder and all its contents with Qt?

I tried using:

QFile::remove();

but it seems like it deletes only one file a time.

Iuliu
  • 4,001
  • 19
  • 31

1 Answers1

48

For Qt5 and above there is QDir::removeRecursively:

QDir dir("C:\\Path\\To\\Folder\\Here");
dir.removeRecursively();

For Qt4 or lower you can use a recursive function that deletes every file:

bool removeDir(const QString & dirName)
{
    bool result = true;
    QDir dir(dirName);

    if (dir.exists(dirName)) {
        Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden  | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
            if (info.isDir()) {
                result = removeDir(info.absoluteFilePath());
            } else {
                result = QFile::remove(info.absoluteFilePath());
            }

            if (!result) {
                return result;
            }
        }
        result = dir.rmdir(dirName);
    }
    return result;
}

as stated here.

Iuliu
  • 4,001
  • 19
  • 31
  • 10
    I deleted the whole directory contains about 700 files source code, fortunately I committed to svn one day before. The `QDir::NoDotAndDotDot` is very important, elsewhere it jumps one height level and then it will delete everything there – Phiber Jul 28 '17 at 15:12