Qt的元对象系统

Q_DECLARE_METATYPE ( Type )
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.


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.


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.


This example shows a typical use case of Q_DECLARE_METATYPE():


 struct MyStruct
 {
     int i;
     ...
 };


 Q_DECLARE_METATYPE(MyStruct)
If MyStruct is in a namespace, the Q_DECLARE_METATYPE() macro has to be outside the namespace:


 namespace MyNamespace
 {
     ...
 }


 Q_DECLARE_METATYPE(MyNamespace::MyStruct)
Since MyStruct is now known to QMetaType, it can be used in QVariant:


 MyStruct s;
 QVariant var;
 var.setValue(s); // copy s into the variant
 ...

 // retrieve the value

 MyStruct s2 = var.value<MyStruct>();

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

int qRegisterMetaType ( const char * typeName )
Registers the type name typeName for the type T. Returns the internal ID used by QMetaType. Any class or struct that has a public default constructor, a public copy constructor and a public destructor can be registered.


After a type has been registered, you can create and destroy objects of that type dynamically at run-time.


This example registers the class MyClass:


 qRegisterMetaType<MyClass>("MyClass");
This function is useful to register typedefs so they can be used by QMetaProperty, or in QueuedConnections


 typedef QString CustomString;
 qRegisterMetaType<CustomString>("CustomString");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值