Skip to content

Instantly share code, notes, and snippets.

@u8sand
Created March 15, 2016 21:25
Show Gist options
  • Save u8sand/dd8623c13c242b2e0697 to your computer and use it in GitHub Desktop.
Save u8sand/dd8623c13c242b2e0697 to your computer and use it in GitHub Desktop.
The new settings class: exploiting JSON and QMetaProperties
#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