Proper way to check QObject derived class type in Qt

心不动则不痛 提交于 2019-12-21 03:47:41

问题


Lets say I have a two classes:

class A : public QObject {};
class B : public QObject {};

then I go

QObject *a = new A();
QObject *b = new B();

now, how do I make sure that "a" is an instance of class A, and "b" is an instance of class B?

currently I do something like this:

if (a->inherits(A::staticMetaObject.className())) {
...
} else if (a->inherits(A::staticMetaObject.className())) {
...

is there a better way?


回答1:


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.



来源:https://stackoverflow.com/questions/1537080/proper-way-to-check-qobject-derived-class-type-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!