bool QObject::inherits(const char *className) const
Returns true if this object is an instance of a class that inherits className or a QObject subclass that inherits className; otherwise returns false.
A class is considered to inherit itself.
Example:
QTimer *timer = new QTimer; // QTimer inherits QObject
timer->inherits("QTimer"); // returns true
timer->inherits("QObject"); // returns true
timer->inherits("QAbstractButton"); // returns false
// QVBoxLayout inherits QObject and QLayoutItem
QVBoxLayout *layout = new QVBoxLayout;
layout->inherits("QObject"); // returns true
layout->inherits("QLayoutItem"); // returns true (even though QLayoutItem is not a QObject)
If you need to determine whether an object is an instance of a particular class for the purpose of casting it, consider using qobject_cast<Type *>(object) instead.
实际使用过程中可以通过 inherits 或者 qobject_cast 转换然后判空来实现此功能
示例:
// 比如我需要判断一个窗口是QMainWindow 还是 QDialog
QMainWindow* ptr = new QMainWindow();if(ptr->inherits("QMainWindow")){// this is a QMainWindow}elseif(ptr->inherits("QDialog")){// this is a QDialog}
Qt 判断对象类型Qt根据属性判断对象的类型Qt根据属性判断对象的类型在使用Qt的过程中偶尔有需求需要动态判断当前对象的类型,比如模板类中若对不同的类型有特殊处理,需要用到此功能,Qt的元对象系统提供了属性来进行判断bool QObject::inherits(const char *className) constReturns true if this object is an instance of a class that inherits className or a QObject