Deleting a folder and all its contents with Qt?

前端 未结 1 2166
情歌与酒
情歌与酒 2021-02-19 11:15

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

I tried using:

QFile::remove();

but it seems like it deletes only one

1条回答
  •  遥遥无期
    2021-02-19 11:39

    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.

    0 讨论(0)
提交回复
热议问题