本文介绍了保存QList< int>到QSettings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将QList<int>保存到我的QSettings中而不循环浏览.
我知道我可以使用writeArray()和循环来保存所有项目或将QList写入QByteArray并将其保存,但是这样在我的INI文件中它就不可读了..

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

当前,我正在使用以下内容将我的QList<int>转换为QList<QVariant>:

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));

并将此QList<Variant>保存到我的设置中,我使用以下代码:

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);

如我所见,QList已正确保存到我的INI文件中(以逗号分隔的整数列表)
但是该函数在退出时崩溃.
我已经尝试过使用指向我的QSettings对象的指针,但是随后在删除指针时崩溃..

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

推荐答案

QSettings :: setValue()需要QVariant作为第二个参数.要将QList作为QVariant传递,您必须将其声明为 Qt元类型.这是演示如何将类型注册为元类型的代码片段:

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;
}

这篇关于保存QList&lt; int&gt;到QSettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 02:12