QT API里关于qobject_cast的描述:

T qobject_cast ( QObject * object )

Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns 0. If object is 0 then it will also return 0.

The class T must inherit (directly or indirectly) QObject and be declared with the Q_OBJECT macro.

A class is considered to inherit itself.

Example:

 

The qobject_cast() function behaves similarly to the standard C++ dynamic_cast(), with the advantages that it doesn't require RTTI support and it works across dynamic library boundaries.

Warning: If T isn't declared with the Q_OBJECT macro, this function's return value is undefined.

大体意思就鼓励大家使用qobject_cast而非dynamic_cast。xxx_cast<TA>(TB),转换是否成功主要看TA/TB是否在一个类继承体系中,TB是否是TA相同类型或者子类。dynamic_cast依赖RTTI类判断,而qobject_cast依赖QMetaObject信息来判断。下面来看看源代码吧:

 

 

 

 

最后说一句,上边说qobject_cast可以跨动态库的。网上没找到有人解释这句话,我猜想,可能意思是支持不同动态库的对象的转换,例如QObject和QWidget,隐含的条件当然是“被转换的对象,都从QObject这个根上继承下来的”,这个就好理解了。

以上就是qobject_cast()相关的代码。读一读然后写一些自己的理解和不懂的地方,收获还是很大的。有问题也请指正。

本文出自 “风码牛不相及” 博客,请务必保留此出处http://wilburwoo.blog.51cto.com/3256629/595337