头文件Config.h
1#pragma once 2 3#include <QVariantMap> 4 5class Config 6{ 7public: 8 Config(const QString &fileName); 9 ~Config(); 10 11 bool open(const QString &fileName); 12 void sync(); 13 14 void write(const QString &key, const QVariant& value); 15 16 QString readString(const QString &key, const QString &default = ""); 17 bool readBool(const QString &key, bool default = false); 18 int readInt(const QString &key, int default = 0); 19 20private: 21 QString m_fileName; 22 23 QVariantMap m_cache; 24};
源文件Config.cpp
1#include "Config.h" 2 3#include <QFile> 4#include <QJsonDocument> 5#include <QJsonObject> 6 7 8Config::Config(const QString &fileName) 9 : m_fileName(fileName) 10{ 11 open(fileName); 12} 13 14Config::~Config() 15{ 16 sync(); 17} 18 19bool Config::open(const QString &fileName) 20{ 21 QFile file(fileName); 22 if (!file.open(QIODevice::ReadOnly)) 23 { 24 return false; 25 } 26 QByteArray allData = file.readAll(); 27 file.close(); 28 29 QJsonParseError jsonError; 30 QJsonDocument jsonDoc = QJsonDocument::fromJson(allData, &jsonError); 31 if (jsonError.error != QJsonParseError::NoError) 32 { 33 return false; 34 } 35 36 QJsonObject root = jsonDoc.object(); 37 m_cache = root.toVariantMap(); 38 39 return true; 40} 41 42void Config::sync() 43{ 44 QJsonObject root = QJsonObject::fromVariantMap(m_cache); 45 QJsonDocument jsonDoc(root); 46 QByteArray data = jsonDoc.toJson(QJsonDocument::Compact); 47 QFile file(m_fileName); 48 if (file.open(QIODevice::WriteOnly)) 49 { 50 file.write(data); 51 file.close(); 52 } 53} 54 55void Config::write(const QString &key, const QVariant &value) 56{ 57 m_cache.insert(key, value); 58} 59 60QString Config::readString(const QString &key, const QString &default) 61{ 62 if (m_cache.contains(key)) 63 { 64 return m_cache.value(key).toString(); 65 } 66 67 return default; 68} 69 70bool Config::readBool(const QString &key, bool default) 71{ 72 if (m_cache.contains(key)) 73 { 74 return m_cache.value(key).toBool(); 75 } 76 77 return default; 78} 79 80int Config::readInt(const QString &key, int default) 81{ 82 if (m_cache.contains(key)) 83 { 84 return m_cache.value(key).toInt(); 85 } 86 87 return default; 88}