==========2017年10月12日更新==========
最近在做安装包,看到qt-installer-framework源码里有相关源代码,以后删除文件夹就可以直接照搬这个了
void removeFiles(const QString &path, bool ignoreErrors){ const QFileInfoList entries = QDir(path).entryInfoList(QDir::AllEntries | QDir::Hidden); foreach (const QFileInfo &fi, entries) { if (fi.isSymLink() || fi.isFile()) { QFile f(fi.filePath()); if (!f.remove()) { const QString errorMessage = QCoreApplication::translate("QInstaller", "Cannot remove file \"%1\": %2").arg( QDir::toNativeSeparators(f.fileName()), f.errorString()); qWarning()<< errorMessage; } } }}static QString errnoToQString(int error){#if defined(Q_OS_WIN) && !defined(Q_CC_MINGW) char msg[128]; if (strerror_s(msg, sizeof msg, error) != 0) return QString::fromLocal8Bit(msg); return QString();#else return QString::fromLocal8Bit(strerror(error));#endif}void removeDirectory(const QString &path, bool ignoreErrors){ if (path.isEmpty()) // QDir("") points to the working directory! We never want to remove that one. return; QStringList dirs; QDirIterator it(path, QDir::NoDotAndDotDot | QDir::Dirs | QDir::NoSymLinks | QDir::Hidden, QDirIterator::Subdirectories); while (it.hasNext()) { dirs.prepend(it.next()); removeFiles(dirs.at(0), ignoreErrors); } QDir d; dirs.append(path); removeFiles(path, ignoreErrors); foreach (const QString &dir, dirs) { errno = 0; if (d.exists(path) && !d.rmdir(dir)) { const QString errorMessage = QCoreApplication::translate("QInstaller", "Cannot remove directory \"%1\": %2").arg(QDir::toNativeSeparators(dir), errnoToQString(errno)); if (!ignoreErrors) qWarning()<< errorMessage; } }}
=====================================================
查过资料好像Qt和windows都没有这样一个接口能直接删除一个不为空的目录。
自己实现了一个,采用递归,估计目录太深堆栈就爆掉了吧
void deleteDir(const QString &d){ QDir dir(d); foreach (QFileInfo inf, dir.entryInfoList(QDir::Dirs|QDir::Files)) { if(inf.isFile()) dir.remove(inf.absoluteFilePath()); else if(inf.isDir() && inf.fileName() != "." && inf.fileName() != "..") deleteDir(inf.absolutePath()+"/"+inf.fileName()); } dir.rmdir(dir.absolutePath());}