32

How to remove a non-empty folder in Qt.

Judge Maygarden
  • 26,961
  • 9
  • 82
  • 99
Viku
  • 2,845
  • 4
  • 35
  • 63

2 Answers2

53

If you're using Qt 5, there is QDir::removeRecursively().

Will Bickford
  • 5,381
  • 2
  • 30
  • 45
hpsMouse
  • 2,004
  • 15
  • 20
43

Recursively delete the contents of the directory first. Here is a blog post with sample code for doing just that. I've included the relevant code snippet.

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

    if (dir.exists()) {
        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 = QDir().rmdir(dirName);
    }
    return result;
}

Edit: The above answer was for Qt 4. If you are using Qt 5, then this functionality is built into QDir with the QDir::removeRecursively() method .

Judge Maygarden
  • 26,961
  • 9
  • 82
  • 99
  • 1
    Seems like will not work for relative paths. removeDir("docs") will check if "docs/docs" exists in the first if. The same problem is in dir.rmdir line. Am I right ? – cybevnm Jan 29 '15 at 16:56
  • @cybevnm: Yes, you are right. I changed the snippet to use the overloaded `exists()` method without parameters. http://doc.qt.io/qt-4.8/qdir.html#exists-2 – Judge Maygarden May 03 '16 at 15:04
  • 1
    The "result = dir.rmdir(dirName)" line has the same defect I believe. I have used QDir().rmdir(dirName) to fix it. – cybevnm May 03 '16 at 15:37