From 4fc87d12f8cc8ff7ac6984e1f63d5901a810de59 Mon Sep 17 00:00:00 2001 From: xmuli Date: Tue, 22 Jun 2021 23:29:53 +0800 Subject: [PATCH] feat: QtMetaAboutClass --- QtMetaAboutClass/QtMetaAboutClass.pro | 20 ++++++++++++ QtMetaAboutClass/m.h | 10 ++++++ QtMetaAboutClass/main.cpp | 47 +++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 QtMetaAboutClass/QtMetaAboutClass.pro create mode 100644 QtMetaAboutClass/m.h create mode 100644 QtMetaAboutClass/main.cpp diff --git a/QtMetaAboutClass/QtMetaAboutClass.pro b/QtMetaAboutClass/QtMetaAboutClass.pro new file mode 100644 index 0000000..80107d8 --- /dev/null +++ b/QtMetaAboutClass/QtMetaAboutClass.pro @@ -0,0 +1,20 @@ +QT -= gui + +CONFIG += c++11 console +CONFIG -= app_bundle + +# You can make your code fail to compile if it uses deprecated APIs. +# In order to do so, uncomment the following line. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +SOURCES += \ + main.cpp + +# Default rules for deployment. +qnx: target.path = /tmp/$${TARGET}/bin +else: unix:!android: target.path = /opt/$${TARGET}/bin +!isEmpty(target.path): INSTALLS += target + +HEADERS += \ + m.h + diff --git a/QtMetaAboutClass/m.h b/QtMetaAboutClass/m.h new file mode 100644 index 0000000..62bbaf3 --- /dev/null +++ b/QtMetaAboutClass/m.h @@ -0,0 +1,10 @@ +#ifndef M_H +#define M_H + +#include +class A:public QObject{ Q_OBJECT}; +class B:public A{ Q_OBJECT}; +class C:public QObject{Q_OBJECT}; +class D:public C{}; + +#endif // M_H diff --git a/QtMetaAboutClass/main.cpp b/QtMetaAboutClass/main.cpp new file mode 100644 index 0000000..838b29e --- /dev/null +++ b/QtMetaAboutClass/main.cpp @@ -0,0 +1,47 @@ +#include "m.h" +#include +#include +using namespace std; + +//使用反射机制获取与类相关的信息 +// 1、QMetaObject 类中获取与类相关的信息的成员函数有 +// const char* className() const; +// 获取类的名称,注意,若某个 QObject 的子类未启动元对象系统(即未使用 Q_OBJECT +// 宏),则该函数将获取与该类最接近的启动了元对象系统的父类的名称,而不再返回 +// 该类的名称,因此建议所有的 QObject 子类都使用 Q_OBJECT 宏。 + +// const QMetaObject* superClass() const; +// //返回父类的元对象,若没有这样的对象则返回 0。  bool inherits(const QMetaObject* mo) const; (Qt5.7) +// //若该类继承自 mo 描述的类型,则返回 true,否则返回 false。类被认为继承自身。 + +// 2、QObject 类中获取与类相关的信息的成员函数有 +// bool inherits(const char* className) const; +// //若该类是className 指定的类的子类则返回true,否则返回false。类被认为继承自身。 + +int main(){ + A ma; + B mb; + C mc; + D md; + + const QMetaObject *pa=ma.metaObject(); + const QMetaObject *pb=mb.metaObject(); + + cout<className()<inherits(pa)<inherits(pb)<inherits(pa)<className()<