简体   繁体   中英

How to store a QMap into a QSetting variable

I'm trying to save some settings in my QT App using QSettings. 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. As you can store a QHash in a QVariant, I would recommend to use a QHash instead of a QMap.

http://doc.qt.io/qt-5/qvariant.html#QVariant-25 and 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

QHash<QString, QVariant> session = settings.value( "session" ).toHash();
for( ... )
{
    QHash<QString,QVariant> data = iterator.value().toHash();
    // do whatever you want with data[ "name" ] etc.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM