编写和读取自定义类到QSettings

时间:2013-08-09 10:11:30

标签: c++ qt serialization qsettings

我需要通过QSettings在注册表中存储自定义类的实例。从Qt的文档中读取后,我认为我已经实现了所需的功能,但我没有设法保存任何东西。

这是我的自定义类:

class SRSDefinition{
public:
    SRSDefinition(QString name, QString definition) : qsName(name), qsDefinition(definition)
    {
        qRegisterMetaType<SRSDefinition>("SRSDefinition");
        qRegisterMetaTypeStreamOperators<SRSDefinition>("SRSDefinition");       
    }
    SRSDefinition(const SRSDefinition& original) : qsName(original.qsName), qsDefinition(original.qsDefinition) {}
    SRSDefinition() : qsName(""), qsDefinition(""){}
    ~SRSDefinition();
    QString qsName;
    QString qsDefinition;
private:
    friend QDataStream& operator << (QDataStream& out, const SRSDefinition& valeur) {out << valeur.qsName << valeur.qsDefinition; return out; }
    friend QDataStream& operator >> (QDataStream& in, SRSDefinition& valeur) {in >> valeur.qsName >> valeur.qsDefinition; return in;}
};
Q_DECLARE_METATYPE(SRSDefinition)
QDataStream& operator << (QDataStream& out, const SRSDefinition& Valeur);
QDataStream& operator >> (QDataStream& in, SRSDefinition& Valeur);

保存在注册表中:

QSettings settings("Organization", "Application");
QVariant variant;
variant.setValue(QVariant::fromValue<SRSDefinition>(m_srsSelected));
settings.setValue("Shared/RecentSRS", variant);

从注册表加载:

QSettings settings("Organization", "Application");
m_srsSelected = settings.value("Shared/RecentSRS").value<SRSDefinition>();

注册表中创建了一个新密钥,但它包含十六进制代码,我认为它只是该类的名称... enter image description here

知道如何有效地存储值吗?

1 个答案:

答案 0 :(得分:18)

使用qRegisterMetaTypeStreamOperators<YourType>("YourType")启用QVariant的自定义类型的序列化/反序列化。此函数使用Qt的元类型系统注册类型的QDataStream输入/输出函数,以便在保存/加载包含自定义类型的变体时调用它们。

#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;
}