qt中创建普通c++类
头文件
#ifndef OPERATION_H
#define OPERATION_H
#include <QFile>
// 默认配置文件路径
const QString FilePath = "./config.json";
typedef struct FileConfig {
QString ip;
QString port;
QString username;
QString password;
QString filepath;
bool is_save_pwd;
}fileConfig;
// 判断目录是否存在
bool isFile(const QString file=FilePath);
// 饿汉模式单例
class FileOperation
{
public:
void writeConfig(fileConfig config);
bool readConif(fileConfig* config);
static FileOperation* getInstance()
{
return pSingleton;
}
private:
static FileOperation *pSingleton;
FileOperation(){}
~FileOperation(){}
FileOperation(FileOperation&){}
};
#endif // OPERATION_H
源文件
// 在头文件初始化会出现重复定义?
FileOperation* FileOperation::pSingleton = new FileOperation;
void FileOperation::writeConfig(fileConfig config)
{
// 保存写入数据
QJsonObject obj;
obj.insert("IP", config.ip);
obj.insert("PORT", config.port);
obj.insert("USERNAME", config.username);
obj.insert("PASSWORD", config.password);
obj.insert("FILEPATH", FilePath);
obj.insert("IS_SAVE", config.is_save_pwd);
QJsonDocument doc(obj);
QByteArray json = doc.toJson();
QFile file(FilePath);
file.open(QIODevice::WriteOnly | QIODevice::Text);
file.write(json.data(), json.size());
file.close();
}
bool FileOperation::readConif(fileConfig* config)
{
if(isFile())
{
QFile file(FilePath);
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray data = file.readAll();
file.close();
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject obj = doc.object();
config->ip = obj.value("IP").toString();
config->port = obj.value("PORT").toString();
config->username = obj.value("USERNAME").toString();
config->password = obj.value("PASSWORD").toString();
config->filepath = obj.value("FILEPATH").toString();
config->is_save_pwd = obj.value("IS_SAVE").toBool();
return true;
}
return false;
}
bool isFile(const QString file)
{
return QFile::exists(file);
}
完整代码在码云上持续更新中。。
https://gitee.com/YiZhiLuGuoDeXiaoMaNong/personnel-management