项目中封装库的对外接口类,包括Qt的插件框架,希望接口类是一个比较干净的类,不需要继承自Object,与Qt无关系,但又需要它的子类使用Qt的信号和槽机制,则可以如下处理。
接口类:
cpp
/* 处理请求 */
#pragma once
#include "../thnetwork_global.h"
#include"IThNetWorkStruct.h"
#include
namespace Network
{
class LIB_EXPORT IHttpNetWorkManager
{
public:
//@brief:获取QObject对象
virtual QObject*getObject()=0;
/* 返回的信号 */
public:
virtual void sigReplyFinish_AcquireOrderInfo(bool success,QString error, Network::ReplyOrderInfo info)=0;
virtual void sigReplyFinish_SubmitPatientInfo(bool success, QString error)=0;
};
}
/*! @brief 获取http管理器 */ extern "C" LIB_EXPORT Network::IHttpNetWorkManager*getHttpNetWorkManager();
实现类.h:
cpp
#pragma once
#include"interface/IThNetWork.h"
#include"interface/IThNetWorkStruct.h"
#include #include class QNetworkReply;
namespace Network {
class HttpNetWorkManager : public QObject,public IHttpNetWorkManager
{
Q_OBJECT
public:
QObject*getObject() { return this; };
public:
HttpNetWorkManager(QObject *parent=nullptr);
~HttpNetWorkManager();
signals:
void sigReplyFinish_AcquireOrderInfo(bool success, QString error, Network::ReplyOrderInfo info) override;
void sigReplyFinish_SubmitPatientInfo(bool success, QString error) override;
private slots:
private:
};
}
连接代码:
cpp
IHttpNetWorkManager*network_manager = getHttpNetWorkManager();
connect(network_manager->getObject(), SIGNAL(sigReplyFinish_AcquireOrderInfo(bool, QString, Network::ReplyOrderInfo)), this,SLOT(slotReplyFinish_AcquireOrderInfo(bool,QString, Network::ReplyOrderInfo)));
可以看到在虚类中声明了两个public的虚函数,子类中声明了同样的两个信号,这样可以实现信号和槽的外部连接。
需要注意的是连接的时候,需要将对象指针转换成QObject*,其次是上面使用的Qt4的连接方式SIGNAL/SLOT,如果使用Qt5的方式 &Class::function 会报错,如果要使用lambanda的方式需要再想办法了。还有一点,信号和槽的自定义类型最好一致且完整,有的地方写Network::ReplyOrderInfo有的直接写ReplyOrderInfo可能会识别不到,从而耽误不必要的时间,我个人做法是尽量写完整Network::ReplyOrderInfo,同样注册类型也是,保证后面不出错。如下面这张图方式声明: