在写抽象类或者接口的时候,肯定是不能继承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宏指定的抽象类