一直觉得用QSettings保存配置信息很方便,为了让程序更够更方便的与Web程序和MongoDB,Redis,PostgreSQL等数据库交互,为QSettings 添加了Json格式支持
源码示例:
https://github.com/tsuibin/Json_format_for_QSettings/blob/master/main.cpp
#include <QApplication> #include <QJsonDocument> #include <QDebug> #include <QVariant> #include <QSettings> bool readJsonFile(QIODevice &device, QSettings::SettingsMap &map) { bool ret = false; QJsonParseError error; map = QJsonDocument::fromJson(device.readAll() , &error).toVariant().toMap(); if( error.error == QJsonParseError::NoError ) ret = true; return ret; } bool writeJsonFile(QIODevice &device, const QSettings::SettingsMap &map) { bool ret = false; QJsonDocument jsonDocument = QJsonDocument::fromVariant(QVariant::fromValue(map)); if ( device.write(jsonDocument.toJson()) != -1 ) ret = true; return ret; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); const QSettings::Format JsonFormat = QSettings::registerFormat("json", readJsonFile, writeJsonFile); QSettings settings(JsonFormat, QSettings::UserScope, "json","cazool"); QMap<QString, QVariant> cazoolData; cazoolData.insert("Address","China"); cazoolData.insert("age",18); cazoolData.insert("Tel","13888888888"); settings.remove("Tsuibin"); settings.setValue("Cazool", QVariant::fromValue(cazoolData)); return a.exec(); }
时间: 2024-10-09 14:06:41