【发布时间】:2016-05-19 20:08:59
【问题描述】:
我正在尝试将自定义类型保存到 QSettings,但在运行时出现错误。这是我要保存的课程:
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <QMetaType>
#include <QString>
class TestClass
{
public:
QString testString;
int testInt;
bool testBool;
};
Q_DECLARE_METATYPE(TestClass)
#endif
这是将类的实例保存到 QSettings 的代码
TestClass test;
test.testString = "Test";
test.testInt = 10;
test.testBool = false;
settings.setValue("TestGroup/TestVal", QVariant::fromValue(test));
settings.sync();
我在运行时得到的错误是:
QVariant::save: unable to save type 'TestClass' (type id: 1032).
ASSERT failure in QVariant::save: "Invalid type to save", file kernel\qvariant.cpp, line 2124
Invalid parameter passed to C runtime function.
Invalid parameter passed to C runtime function.
根据文档,该类必须提供默认构造函数、析构函数和复制构造函数。对于这个类,自动生成的构造函数、析构函数和复制构造函数就足够了,所以我没有提供一个(尽管我确实尝试过,看看是否是问题所在)。我还使用了 Q_DECLARE_METATYPE(),所以 QMetaType 知道该类,所以据我所知,我已经满足使用 QVariant 类的要求。
我错过了什么?
【问题讨论】: