qtqt4

Removing a non empty folder in Qt


How to remove a non-empty folder in Qt.


Solution

  • 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 .