Save QList<int> to QSettings

你说的曾经没有我的故事 提交于 2019-12-17 23:42:50

问题


I want to save a QList<int> to my QSettings without looping through it.
I know that I could use writeArray() and a loop to save all items or to write the QList to a QByteArray and save this but then it is not human readable in my INI file..

Currently I am using the following to transform my QList<int> to QList<QVariant>:

QList<QVariant> variantList;
//Temp is the QList<int>
for (int i = 0; i < temp.size(); i++)
  variantList.append(temp.at(i));

And to save this QList<Variant> to my Settings I use the following code:

QVariant list;
list.setValue(variantList);
//saveSession is my QSettings object
saveSession.setValue("MyList", list);

The QList is correctly saved to my INI file as I can see (comma seperated list of my ints)
But the function crashes on exit.
I already tried to use a pointer to my QSettings object instead but then it crashes on deleting the pointer ..


回答1:


QSettings::setValue() needs QVariant as a second parameter. To pass QList as QVariant, you have to declare it as a Qt meta type. Here's the code snippet that demonstrates how to register a type as meta type:

#include <QCoreApplication>
#include <QDebug>
#include <QMetaType>
#include <QSettings>
#include <QVariant>

Q_DECLARE_METATYPE(QList<int>)

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qRegisterMetaTypeStreamOperators<QList<int> >("QList<int>");

    QList<int> myList;
    myList.append(1);
    myList.append(2);
    myList.append(3);

    QSettings settings("Moose Soft", "Facturo-Pro");
    settings.setValue("foo", QVariant::fromValue(myList));
    QList<int> myList2 = settings.value("foo").value<QList<int> >();
    qDebug() << myList2;

    return 0;
}



回答2:


You might have to register QList as a meta-type of its own for it to work. This is a good starting point to read up on meta-types in Qt: http://qt.nokia.com/doc/4.6/qmetatype.html#details .



来源:https://stackoverflow.com/questions/2452893/save-qlistint-to-qsettings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!