-->

Deleting a folder and all its contents with Qt?

2020-08-14 09:49发布

问题:

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.

回答1:

For Qt5 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.



标签: c++ qt