[英]How to store a QMap into a QSetting variable
I'm trying to save some settings in my QT App using QSettings. 我正在尝试使用QSettings在我的QT应用程序中保存一些设置。 For that i have defined a type: 为此,我定义了一个类型:
typedef QMap
<
QString,
QMap<QString, QVariant>
>
QSession;
After that i have registred it 之后,我已经注册了它
Q_DECLARE_METATYPE(QSession);
To create some entries and read them after at runtime make no problems, BUT i get the folowing error closing the app 要创建一些条目并在运行时读取它们后没有问题,但我在关闭应用程序时遇到以下错误
QVariant::save: unable to save type 'QSession' (type id: 1067).
My save-Function looks like that 我的保存功能看起来像这样
void saveSession()
{
QSession session;
for(auto it = pool.begin(); it != pool.end(); ++it)
{
QString hash(toQString((*it).getHash()));
session[hash]["name"] = toQVariant(toQString((*it).getName()));
session[hash]["size"] = toQVariant((*it).getSize());
session[hash]["timeout"] = toQVariant((*it).getTimeout());
}
this->settings.setValue("session", QVariant::fromValue(session));
}
Where is the problem? 问题出在哪儿? Thanks! 谢谢!
您必须为QSession
类型注册流操作符-请参阅qRegisterMetaTypeStreamOperators 。
QSettings can serialize QVariants. QSettings可以序列化QVariant。 As you can store a QHash in a QVariant, I would recommend to use a QHash instead of a QMap. 由于您可以将QHash存储在QVariant中,因此我建议使用QHash而不是QMap。
http://doc.qt.io/qt-5/qvariant.html#QVariant-25 and http://doc.qt.io/qt-5/qvariant.html#toHash http://doc.qt.io/qt-5/qvariant.html#QVariant-25和http://doc.qt.io/qt-5/qvariant.html#toHash
void saveSession()
{
QHash<QString,QVariant> session;
for(auto it = pool.begin(); it != pool.end(); ++it)
{
QString hash(toQString((*it).getHash()));
QHash<QString, QVariant> tmp;
tmp[ "name" ] = toQVariant(toQString((*it).getName()));
tmp[ "size" ] = toQVariant((*it).getSize());
tmp[ "timeout" ] = toQVariant((*it).getTimeout());
session.insert( hash, QVariant( tmp ) );
}
this->settings.setValue( "session", session );
}
This code is untested, but I guess it should do what you expect. 该代码未经测试,但是我想它应该可以完成您期望的工作。 To get the values from your QSettings object, you can do 要从QSettings对象获取值,您可以执行
QHash<QString, QVariant> session = settings.value( "session" ).toHash();
for( ... )
{
QHash<QString,QVariant> data = iterator.value().toHash();
// do whatever you want with data[ "name" ] etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.