我需要通过QSettings将自定义类的实例存储在注册表中。从Qt的文档中阅读后,我认为我已经实现了所需的功能,但是我什么也没做。

这是我的自定义类(class):

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>();

在注册表中创建了一个新键,但是它包含十六进制代码,我认为这只是该类的名称...

任何想法如何有效地存储值?

最佳答案

使用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;
}

关于c++ - 编写和读取自定义类到QSettings,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18144377/

10-11 22:46