Writing and reading custom class to QSettings

蓝咒 提交于 2019-11-28 23:34:56

Use qRegisterMetaTypeStreamOperators<YourType>("YourType") to enable serialization/de-serialization of custom types with QVariant. This function registers your type's QDataStream input/output functions with Qt's metatype system so that it can invoke them when saving/loading a variant containing your custom type.

#include <QtCore/QDebug>
#include <QtCore/QDataStream>
#include <QtCore/QSettings>

struct CustomType {
    QString name;
    int age;
};

Q_DECLARE_METATYPE(CustomType);

QDataStream& operator<<(QDataStream& out, const CustomType& v) {
    out << v.name << v.age;
    return out;
}

QDataStream& operator>>(QDataStream& in, CustomType& v) {
    in >> v.name;
    in >> v.age;
    return in;
}

int main(int,char**) {

    qRegisterMetaTypeStreamOperators<CustomType>("CustomType");

    {
        CustomType t;
        t.name = "John Smith";
        t.age = 42;
        QSettings s("config.ini", QSettings::IniFormat);
        s.setValue("user", QVariant::fromValue(t));
    }

    {
        QSettings s("config.ini", QSettings::IniFormat);
        QVariant value = s.value("user");
        CustomType t = value.value<CustomType>();

        qDebug() << t.name << t.age;
    }


    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!