Qt使用Q_DECLARE_INTERFACE Q_INTERFACES宏实现接口类使用qobject_cast进行类型转换

在写抽象类或者接口的时候,肯定是不能继承QObject的

但是又想使用qobject_cast进行类型转换,使用以下办法就能实现

cpp 复制代码
#ifndef FACTORYINTERFACE_H__
#define FACTORYINTERFACE_H__
#include <QObject>
class FactoryInterface{
public:
	FactoryInterface() {};
	virtual ~FactoryInterface() {};

};

QT_BEGIN_NAMESPACE
Q_DECLARE_INTERFACE(FactoryInterface, "DetectionSoftware.Factory.FactoryInterface")//一定是唯一的标识符
QT_END_NAMESPACE

#endif // FACTORYINTERFACE_H__
cpp 复制代码
/*
* 这个抽象类继承自FactoryInterface抽象类
* 
*/

#ifndef FACTORYINTERFACE1_0_H__
#define FACTORYINTERFACE1_0_H__
#include "FactoryInterface.h"

class FactoryInterface1_0: public  FactoryInterface{
public:
	FactoryInterface1_0() {};
	virtual ~FactoryInterface1_0() {};

signals:


public slots:


};

QT_BEGIN_NAMESPACE
Q_DECLARE_INTERFACE(FactoryInterface1_0, "DetectionSoftware.Factory.FactoryInterface1_0")//一定是唯一的标识符
QT_END_NAMESPACE
#endif // FACTORYINTERFACE1_0_H__
cpp 复制代码
#ifndef FACTORYIMPLEMENT1_0_H__
#define FACTORYIMPLEMENT1_0_H__

#include <QObject>
#include "factoryInterface1_0.h"
class FactoryImplement1_0  : public QObject, public FactoryInterface1_0{
	Q_OBJECT
		Q_INTERFACES(FactoryInterface FactoryInterface1_0)

public:
	FactoryImplement1_0(QObject *parent = nullptr);
	~FactoryImplement1_0();
};


#endif // FACTORYIMPLEMENT1_0_H__

直接看代码,重点就是

Q_INTERFACES(FactoryInterface FactoryInterface1_0)

Q_DECLARE_INTERFACE(FactoryInterface1_0, "DetectionSoftware.Factory.FactoryInterface1_0")//一定是唯一的标识符

这两个宏,具体作用不赘述。

然后使用

cpp 复制代码
	QObject* test = new FactoryImplement1_0();
	FactoryInterface* t = qobject_cast<FactoryInterface*>(test);
	FactoryInterface1_0* tt = qobject_cast<FactoryInterface1_0*>(test);

注意

要想qobject_cast能用,实现类必须使用Q_INTERFACES指定转换的抽象类

只能从QObject类型转为Q_INTERFACES宏指定的抽象类

相关推荐
功德+n6 小时前
Linux下安装与配置Docker完整详细步骤
linux·运维·服务器·开发语言·docker·centos
明日清晨6 小时前
python扫码登录dy
开发语言·python
阿里小阿希6 小时前
CentOS7 PostgreSQL 9.2 升级到 15 完整教程
数据库·postgresql
我是唐青枫6 小时前
C#.NET gRPC 深入解析:Proto 定义、流式调用与服务间通信取舍
开发语言·c#·.net
荒川之神6 小时前
Oracle 数据仓库雪花模型设计(完整实战方案)
数据库·数据仓库·oracle
JJay.6 小时前
Kotlin 高阶函数学习指南
android·开发语言·kotlin
bazhange6 小时前
python如何像matlab一样使用向量化替代for循环
开发语言·python·matlab
jinanwuhuaguo6 小时前
截止到4月8日,OpenClaw 2026年4月更新深度解读剖析:从“能力回归”到“信任内建”的范式跃迁
android·开发语言·人工智能·深度学习·kotlin
做个文艺程序员6 小时前
MySQL安全加固十大硬核操作
数据库·mysql·安全
froginwe116 小时前
CSS 创建:从基础到高级
开发语言