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宏指定的抽象类

相关推荐
Mr_Xuhhh7 分钟前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
Fireworkitte10 分钟前
Redis 源码 tar 包安装 Redis 哨兵模式(Sentinel)
数据库·redis·sentinel
纳兰青华17 分钟前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
好开心啊没烦恼20 分钟前
Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
开发语言·python·数据挖掘·数据分析
liulilittle22 分钟前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
Devil枫32 分钟前
Kotlin高级特性深度解析
android·开发语言·kotlin
ChinaDragonDreamer34 分钟前
Kotlin:2.1.20 的新特性
android·开发语言·kotlin
qq_3392822343 分钟前
postgressql 如何修改模式的所有表的所有者
数据库
安之若素^1 小时前
启用不安全的HTTP方法
java·开发语言