Removing a non empty folder in Qt

2020-02-08 03:58发布

问题:

How to remove a non-empty folder in Qt.

回答1:

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 .



回答2:

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



标签: qt qt4