自定义数据结构通过QVariant来存储并通过QMetaType来判断对应存储类型

一般常用的int double等数据类型判别和代码用例网上有很多,这里不做描述,这里只讲自定义数据类型和QVariant的转换操作。

(1) 自定义数据类型

 

 

自定义数据类型

注意一定要使用Q_DECLARE_METATYPE() 对自定义数据类型进行宏定义,否则无法转换成QVariant

(2) 使用

① 自定义类型转QVariant

 

② QVariant转成自定义数据类型

 

(3) 注意一定要对自定义类型通过Q_DECLARE_METATYPE()进行宏定义转换,Qt5.5.0文档中解释如下;

① Q_DECLARE_METATYPE( Type)

1) This macro makes the type Type known to QMetaType as long as it provides a public default constructor, a public copy constructor and a public destructor. It is needed to use the type Type as a custom type in QVariant.

2) This macro requires that Type is a fully defined type at the point where it is used. For pointer types, it also requires that the pointed to type is fully defined. Use in conjunction with Q_DECLARE_OPAQUE_POINTER() to register pointers to forward declared types.

3) Ideally, this macro should be placed below the declaration of the class or struct. If that is not possible, it can be put in a private header file which has to be included every time that type is used in a QVariant.

4) Adding a Q_DECLARE_METATYPE() makes the type known to all template based functions, including QVariant. Note that if you intend to use the type in queued signal and slot connections or in QObject's property system, you also have to call qRegisterMetaType() since the names are resolved at runtime.

② 硬核翻译说明:

1) 只要该宏提供了公共默认构造函数、公共复制构造函数和公共析构函数,它就会使QMetaType知道该类型。QVariant中,需要将该类型用作自定义类型

2) 此宏要求该类型在使用时是完全定义的类型。对于指针类型,它还要求完全定义指向的类型。Q_DECLARE_OPAQUE_POINTER()结合使用,将指针注册到前向声明的类型。

3) 理想情况下,这个宏应该放在类或结构声明的下面。如果这是不可能的,它可以放在一个私有头文件中,每次在QVariant中使用该类型时都必须包含该头文件

4) 添加Q_DECLARE_METATYPE()可以使所有基于模板的函数(包括QVariant)都知道该类型。请注意,如果要在排队信号和插槽连接QObject的属性系统中使用该类型,还必须调用qRegisterMetaType(),因为名称在运行时解析

posted @ 2021-11-23 09:40  SmartGame  阅读(1242)  评论(0编辑  收藏  举报