当前位置: 首页 > news >正文

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”);

}
}


http://www.mrgr.cn/news/103.html

相关文章:

  • IBMS管理平台,推动建筑行业向智能化发展
  • 鸿蒙装饰器的介绍
  • 贪吃蛇(C语言详解)
  • SOM-RK3399基于Debian系统安装Docker
  • 小程序学习day07-页面配置、网络数据请求、页面导航-声明式导航、编程式导航
  • 查询接口优化(线程池异步调用)
  • 容器构建superset
  • 云计算29-------mysql主从数据库(5.7版本)与python的交互及mycat
  • 电脑音频转文字软件哪个好?不容错过的免费音频转文字软件大盘点
  • 17.1 HTTP协议与Web架构
  • 微信小程序的四种弹窗使用
  • Arthas 学习笔记
  • CSS 的文字描边属性text-stroke
  • XSS Game靶场练习
  • 【机器学习第11章——特征选择与稀疏学习】
  • 决策支持系统:智能化决策的核心要点|DSS|数据|模型|界面|模拟|预测|知识库
  • 【漫谈C语言和嵌入式004】深入理解RS232、RS422和RS485:嵌入式系统中的串行通信协议
  • 递归--数据结构--黑马
  • 微服务架构设计中的常见的10种设计模式
  • 趋动科技成为GSMA 5G IN创新会员,专注于软件定义AI算力技术