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().