Created
March 15, 2016 21:25
-
-
Save u8sand/dd8623c13c242b2e0697 to your computer and use it in GitHub Desktop.
The new settings class: exploiting JSON and QMetaProperties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "settings.h" | |
#include <QFile> | |
#include <QVariantMap> | |
#include <QJsonDocument> | |
#include <QMetaProperty> | |
#include "util.h" | |
Settings::Settings(QObject *parent): | |
QObject(parent) | |
{ | |
} | |
void Settings::LoadSettings() | |
{ | |
QFile f(Util::SettingsLocation()); | |
if(f.open(QIODevice::ReadOnly | QIODevice::Text)) | |
{ | |
QVariantMap settings = QJsonDocument::fromJson(f.readAll()).toVariant().toMap(); | |
f.close(); | |
for(QVariantMap::iterator setting = settings.begin(); setting != settings.end(); setting++) | |
setProperty(setting.key().toUtf8(), setting.value()); | |
} | |
} | |
void Settings::SaveSettings() | |
{ | |
QObject *obj; // todo | |
QFile f(Util::SettingsLocation()); | |
if(f.open(QFile::WriteOnly | QFile::Truncate | QIODevice::Text)) | |
{ | |
f.write(QJsonDocument::fromVariant(UserPropertyMap(obj)).toJson()); | |
f.close(); | |
} | |
} | |
QVariantMap Settings::UserPropertyMap(QObject *obj) | |
{ | |
QVariantMap properties; | |
const QMetaObject *mobj = obj->metaObject(); | |
for(int i = mobj->propertyCount()-1; i >= 0; --i) | |
{ | |
QMetaProperty mprop = mobj->property(i); | |
const char *name = mprop.name(); | |
if(mprop.isUser()) | |
properties[name] = obj->property(name); | |
} | |
return properties; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment