// reflexdemo.h
#ifndef REFLEXDEMO_H
#define REFLEXDEMO_H
#include <QObject>
class ReflexDemo : public QObject {
Q_OBJECT
public:
explicit ReflexDemo(QObject *parent = nullptr);
Q_INVOKABLE void public_method(int a);
void no_q_invokable_public_method(int a);
Q_PROPERTY(int public_field MEMBER p_field)
int p_field;
protected:
Q_INVOKABLE void protected_method(int a);
void no_q_invokable_protected_method(int a);
Q_PROPERTY(int protected_field)
signals:
void demo_signal();
protected slots:
void demo_slot();
private:
Q_INVOKABLE void private_method(int a);
void no_q_invokable_private_method(int a);
Q_PROPERTY(int private_field)
};
#endif // REFLEXDEMO_H
// main.cc
#include "reflexdemo.h"
#include <QCoreApplication>
#include <QDebug>
#include <QMetaObject>
#include <QMetaProperty>
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
ReflexDemo rd;
auto meta_obj = rd.metaObject();
qInfo() << "class name: " << meta_obj->className();
auto property_count = meta_obj->propertyCount();
qInfo() << "property_count: " << property_count;
for (int i = 0; i < property_count; ++i) {
auto property = meta_obj->property(i);
qInfo() << "property[" << i << "] is " << property.name();
}
auto method_count = meta_obj->methodCount();
qInfo() << "method_count: " << method_count;
for (int i = 0; i < method_count; ++i) {
auto method = meta_obj->method(i);
qInfo() << "method[" << i << "] is " << method.name();
}
// rd.public_field
// rd.protected_field
// rd.private_field
rd.setProperty("public_field", 100);
auto value = rd.property("public_field").toInt();
qInfo() << "public_field value:" << value;
rd.setProperty("protected_field", 33);
value = rd.property("protected_field").toInt();
qInfo() << "protected_field value:" << value;
return a.exec();
}
输出
class name: ReflexDemo
property_count: 4
property[ 0 ] is objectName
property[ 1 ] is public_field
property[ 2 ] is protected_field
property[ 3 ] is private_field
method_count: 10
method[ 0 ] is "destroyed"
method[ 1 ] is "destroyed"
method[ 2 ] is "objectNameChanged"
method[ 3 ] is "deleteLater"
method[ 4 ] is "_q_reregisterTimers"
method[ 5 ] is "demo_signal"
method[ 6 ] is "demo_slot"
method[ 7 ] is "public_method"
method[ 8 ] is "protected_method"
method[ 9 ] is "private_method"
public_field value: 100
ReflexDemo::setProperty: Property "protected_field" invalid, read-only or does not exist
ReflexDemo::property: Property "protected_field" invalid or does not exist
protected_field value: 0
- 结论
类的成员要加入到qt的反射机制中,必须继承QObject ,在方法前加 Q_INVOKABLE,
qt的property不等类的成员变量
Q_PROPERTY(type name
(READ getFunction [WRITE setFunction] |
MEMBER memberName [(READ getFunction | WRITE setFunction)])
[RESET resetFunction]
[NOTIFY notifySignal]
[REVISION int]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
[USER bool]
[CONSTANT]
[FINAL])