qt反射之类反射、方法反射、字段反射

话不多说,直接上代码:

main.cpp:

#include < QCoreApplication >

#include "fstudent.h"

#include "manage.h"

int main(int argc, char *argv[])

{

QCoreApplication a(argc, argv);

//注册类型

qRegisterMetaType("FStudent");

复制代码
Manage manage;
manage.print();

return a.exec();

}

反射类头文件:fstudent.h

#ifndef FSTUDENT_H

#define FSTUDENT_H

/*

1、这个类必须直接或间接继承自QObject

2、这个类必须写上Q_OBJECT宏定义

3、需要将类注册到元对象系统中

4、构造函数必须声明可调用

*/

#include

#include

#include

class FStudent : public QObject

{

//元对象系统必须添加 Q_OBJECT 引入元对象

Q_OBJECT

//实现属性m_Name反射,需要下面声明:

Q_PROPERTY(QString m_Name MEMBER m_Name)

public:

//构造函数必须用Q_INVOKABLE 进行修饰,不然该类无法做到反射

Q_INVOKABLE explicit FStudent(QObject *parent=nullptr);

复制代码
~FStudent();
//该方法如果要做到反射,以下任一一个可以做到
//1、 添加 Q_INVOKABLE修饰
//2、 加slots
//3、加signals
Q_INVOKABLE void print();

public slots:

private:

复制代码
QString m_Name;

};

Q_DECLARE_METATYPE(FStudent)

#endif // FSTUDENT_H

反射类源文件:fstudent.cpp

#include "fstudent.h"

#include

FStudent::FStudent(QObject *parent):QObject(parent)

{

}

FStudent::~FStudent()

{

}

void FStudent::print()

{

qDebug() << this->m_Name;

}

管理反射类头文件:manage.h

#ifndef MANAGE_H

#define MANAGE_H

#include

#include

class Manage

{

public:

Manage();

QList<QObject*> stu_obj_list;

void print();

};

#endif // MANAGE_H

管理反射类源文件:manage.cpp

#include "manage.h"

#include

#include

#include

#include

#include

#include

Manage::Manage()

{

//QT6.5.3下可用,在qt5.12.10下不可用

const QMetaObject* MetaObject = QMetaType::fromName("FStudent").metaObject();

//以下在qt5.12.10下不可用

//int typenumber = QMetaType::type("FStudent");

复制代码
//const QMetaObject* MetaObject = QMetaType::metaObjectForType(typenumber);

if(MetaObject == nullptr)
{
    qDebug() << "get FStudent MetaObject failed!!!";
    return;
}

QStringList stu_name_list;
stu_name_list << "张三" << "李四" <<"王二" <<"赵六";

for(auto& stu_name:stu_name_list)
{
    QObject* stu_obj = MetaObject->newInstance();

    stu_obj->setProperty("m_Name",QVariant(stu_name));



    stu_obj_list.push_back(stu_obj);
}

}

void Manage::print()

{

for(auto& stu_obj:stu_obj_list)

{

//通过反射属性来打印信息

qDebug() << stu_obj->property("m_Name").toString();

//通过反射方法来打印信息

QMetaObject::invokeMethod(stu_obj,"print");

}

}

相关推荐
攻城狮7号1 分钟前
【AI时代速通QT】第十节:在 Windows 上配置vs和qmake环境手动编译 Qt 项目
windows·qt·makefile·visual studio·qmake·vcvarsall·nmake/jom
渔舟唱晚@6 分钟前
从原理到实现:基于 Y.js 和 Tiptap 的实时在线协同编辑器全解析
开发语言·javascript·编辑器
Boop_wu7 分钟前
[Java EE] 网络编程套接字
开发语言·单片机·php
亮子AI8 分钟前
chart.js 雷达图顶部标题怎样消除?
开发语言·前端·javascript·chart.js
兩尛8 分钟前
查找接口成功率最优时间段 (c卷)
c语言·开发语言·算法
0和1的舞者10 分钟前
《Spring Bean&DI 通关笔记:从定义到注入的全场景避坑指南》
java·开发语言·学习·spring·ioc·di·web
tryxr10 分钟前
synchronized
java·开发语言·锁机制·锁升级·synchronized 锁
2401_8534482311 分钟前
imx6ullMini开发板qt项目
qt·系统移植
_OP_CHEN12 分钟前
【从零开始的Qt开发指南】(八)Qt 常用控件之显示类控件(上):Label 与 LCD Number 实战指南
开发语言·c++·qt·前端开发·图形化界面·qt常用控件·企业级组件
拾忆,想起15 分钟前
Dubbo健康检查全攻略:构建高可观测与高可用的微服务基座
开发语言·微服务·云原生·架构·php·dubbo·safari