我正在使用Qt编写序列化程序。
我使用QObject
的{{1}}来使用Q_PROPERTY
类。
课程如下:
QMetas
类和列表都使用class Person : public QObject
{
Q_OBJECT
Q_PROPERTY(QString firstname READ firstname WRITE setFirstName)
Q_PROPERTY(int age READ age WRITE setAge)
public:
Person();
Person(const Person &other);
Person &operator=(const Person &other);
/* READ & WRITE accessors are implemented */
};
class Enterprise : public QObject
{
Q_OBJECT
Q_PROPERTY(Person owner READ owner WRITE setOwner)
Q_PROPERTY(QList<Person> employees READ employees WRITE setEmployees)
public:
Enterprise();
Enterprise(const Enterprise &other);
Enterprise &operator=(const Enterprise &other);
/* READ & WRITE accessors are implemented */
};
和Q_DECLARE_METATYPE
声明。
然后我想用以下方法保存数据:
qRegisterMetaType
除了带有列表的属性外,它适用于所有内容。只要QVariantMap serializer(const QObject &object)
{
const QMetaObject *mo = object.metaObject();
QVariantMap varmap;
for(int pid = 0; pid < mo->propertyCount(); ++pid)
{
QMetaProperty mp = mo->property(pid);
QString pName = QString::fromLatin1(mp.name());
if(pName.toLower() == "objectname")
continue;
QVariant vdata = mp.read(&object);
if(mp.type() == QVariant::UserType)
{
int metaTypeId = QMetaType::type(mp.typeName());
if(metaTypeId != QMetaType::UnknownType)
{
void *data = QMetaType::create(metaTypeId, vdata.data());
QObject *subobject = static_cast<QObject*>(data);
vdata = serializer(*subobject);
QMetaType::destroy(metaTypeId, data);
data = 0;
}
}
varmap.insert(pName, vdata);
}
return varmap;
}
不是QList
,此声音就会正常。那我该怎么办?