-
Notifications
You must be signed in to change notification settings - Fork 1
/
setting.cpp
64 lines (61 loc) · 1.71 KB
/
setting.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "setting.h"
#include <string>
#include <qfile.h>
#include <qiodevice.h>
#include <qjsonobject.h>
#include <qjsonarray.h>
#include <qjsondocument.h>
#include <qmessagebox.h>
#include <fstream>
Config::Config()
{
}
QJsonValue Config::Get(QString key)
{
return object.value(key);
}
int Config::Set(QString key, QString value)
{
object.insert(key,value);
return 0;
}
int Config::Read()
{
std::fstream _file;
_file.open("config.json", std::ios::in);//检测是否存在;配置文件
if (_file)
{
_file.close();
QFile file("config.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);//打开文件
QString value = file.readAll();//读取
file.close();
QJsonParseError parseJsonErr;
QJsonDocument document = QJsonDocument::fromJson(value.toUtf8(), &parseJsonErr);
qDebug() << parseJsonErr.error;
if (!(parseJsonErr.error == QJsonParseError::NoError))
{
QMessageBox box(QMessageBox::Critical,"错误", "读取配置文件失败:"+ QString::fromStdString(std::to_string(parseJsonErr.error)));
box.exec();
return -1;
}
object = document.object();//将配置设置为根据配置文件构建的QJsonObject
}
else
{
QMessageBox box(QMessageBox::Information, "提示", "未找到配置文件,将使用默认配置");
box.exec();
}
return 0;
}
int Config::Save()
{
QJsonDocument doc;
doc.setObject(object);
QByteArray data = doc.toJson();//也不知道为什么要这么复杂的操作
QFile file("config.json");//json写入文件
file.open(QIODevice::WriteOnly);
file.write(data);
file.close();
return true;
}