tags:

views:

492

answers:

2

Hello,

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 ..

A: 

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 .

e8johan
Yes it is working after registering as a metatype (although it is saved as a bytestream).. But there is no error, when I pass a QList<QVariant> to setValue. Therefore I expect it to work.. And if I look at the INI file, the list is saved comma seperated with the values in it, only the destructor of the QList crashes for some reason...
Tobias
+2  A: 

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 <QVariant>

Q_DECLARE_METATYPE(QList<int>)

void output(const QVariant &var)
{
    qDebug() << var.value< QList<int> >();
}

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

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

    output(QVariant::fromValue< QList<int> >(myList));

    return 0;
}
chalup
Hmm.. I know how to use metatypes, I am using them already. But if I declare my QList<int> as metatype and save it to my settings, the data is saved as bytestream.. means that no one can read / change it directly in the ini .. But no crash occurs!! :)
Tobias