temporarydirectory.h
#pragma once
#include "utils_global.h"
#include <QTemporaryDir>
namespace Utils {
class QTCREATOR_UTILS_EXPORT TemporaryDirectory : public QTemporaryDir
{
public:
explicit TemporaryDirectory(const QString &pattern);
static QTemporaryDir *masterTemporaryDirectory();
static void setMasterTemporaryDirectory(const QString &pattern);
static QString masterDirectoryPath();
};
} // namespace Utils
temporarydirectory.cpp
#include "temporarydirectory.h"
#include <QtCore/QCoreApplication>
#include "qtcassert.h"
namespace Utils {
static QTemporaryDir* m_masterTemporaryDir = nullptr;
static void cleanupMasterTemporaryDir()
{
delete m_masterTemporaryDir;
m_masterTemporaryDir = nullptr;
}
TemporaryDirectory::TemporaryDirectory(const QString &pattern) :
QTemporaryDir(m_masterTemporaryDir->path() + '/' + pattern)
{
//QTC_CHECK(!QFileInfo(pattern).isAbsolute());
}
QTemporaryDir *TemporaryDirectory::masterTemporaryDirectory()
{
return m_masterTemporaryDir;
}
void TemporaryDirectory::setMasterTemporaryDirectory(const QString &pattern)
{
if (m_masterTemporaryDir)
cleanupMasterTemporaryDir();
else
qAddPostRoutine(cleanupMasterTemporaryDir);
m_masterTemporaryDir = new QTemporaryDir(pattern);
}
QString TemporaryDirectory::masterDirectoryPath()
{
return m_masterTemporaryDir->path();
}
} // namespace Utils
用法:
// 创建临时文件夹:
Utils::TemporaryDirectory::setMasterTemporaryDirectory(QDir::tempPath() + "/QtCreator-XXXXXX");
// 获取临时文件夹:
QString tempDirPath = Utils::TemporaryDirectory::masterTemporaryDirectory();
例子出自:Qt Creator源码