本文介绍了在 Qt 中检查 QObject 派生类类型的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个类:
class A : public QObject {};
class B : public QObject {};
那我去
QObject *a = new A();
QObject *b = new B();
现在,我如何确保a"是 A 类的实例,而b"是 B 类的实例?
now, how do I make sure that "a" is an instance of class A, and "b" is an instance of class B?
目前我做这样的事情:
if (a->inherits(A::staticMetaObject.className())) {
...
} else if (a->inherits(A::staticMetaObject.className())) {
...
有更好的方法吗?
推荐答案
您可以在 QObject 派生类上使用 qobject_cast(instance)
并检查返回值.如果 instance
无法转换为 MyClass*
,则返回值为 NULL.
You can use qobject_cast<MyClass*>(instance)
on QObject derived classes and check the return value. If instance
cannot be cast to MyClass*
, the return value will be NULL.
这篇关于在 Qt 中检查 QObject 派生类类型的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!