我需要通过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>();
创建注册表中的新键,但它包含十六进制代码,我认为只是类的名称…
任何想法如何有效地存储价值?
解决方法
使用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; }