diff --git a/QtQMetaProperty/QtQMetaProperty.pro b/QtQMetaProperty/QtQMetaProperty.pro new file mode 100644 index 0000000..b6cc0fe --- /dev/null +++ b/QtQMetaProperty/QtQMetaProperty.pro @@ -0,0 +1,19 @@ +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/QtQMetaProperty/m.h b/QtQMetaProperty/m.h new file mode 100644 index 0000000..48c0056 --- /dev/null +++ b/QtQMetaProperty/m.h @@ -0,0 +1,16 @@ +#ifndef M_H //要使用元对象系统,需在头文件中定义类。 +#define M_H + +#include +#include +using namespace std; + +class Z:public QObject{ + Q_OBJECT +public: + Q_PROPERTY(int b READ gb WRITE sb) + int gb(){return m_mb;} + void sb(int x){m_mb=x;} + int m_mb; +}; +#endif // M_H diff --git a/QtQMetaProperty/main.cpp b/QtQMetaProperty/main.cpp new file mode 100644 index 0000000..e2e87f6 --- /dev/null +++ b/QtQMetaProperty/main.cpp @@ -0,0 +1,18 @@ +// 使用反射机制获取属性的信息 +// 使用 QMetaObject 成员函数存取属性值 + +#include "m.h" +#include +int main(int argc, char *argv[]) +{ + Z mz; + const QMetaObject *p = mz.metaObject(); + QMetaProperty pe = p->property(p->indexOfProperty("b")); + + cout << pe.name()<< endl; + cout << pe.typeName()<< endl; + pe.write(&mz, 14); + cout << pe.read(&mz).value()<