关于qt自定义事件的理论知识,请参考如下博文,我直接贴代码
参考一、https://www.cnblogs.com/liushui-sky/p/5733525.html
参考二、http://blog.chinaunix.net/uid-24219701-id-4044098.html
场景描述,lightDPS是开关灯的控制类,在应用程序中需要在多个业务流程中对灯进行开关控制,虽然使用信号和槽也能实现,但当业务流程增加时,又得定义信号/槽,不如使用事件简洁方便。
事件类myevent.h
#ifndef MYEVENT_H
#define MYEVENT_H
#include <QObject>
#include <QEvent>
//声明、定义、注册自定义事件类型,事件ID为自定义事件ID起点QEvent::User +100=1100
class myLightEvent : public QEvent
{
public:
myLightEvent() : QEvent(myLightEvent::type())
{}
virtual ~myLightEvent()
{}
static QEvent::Type type()
{
if (lightEventType == QEvent::None)
{
int generatedType = QEvent::registerEventType(QEvent::User+100);
lightEventType = static_cast<QEvent::Type>(generatedType);
}
return lightEventType;
}
void setLightAction(int action)
{
lightAction = action;
}
int getLightAction()
{
return lightAction;
}
private:
int lightAction;
static QEvent::Type lightEventType;
};
//监控者
class MyWatcher: public QObject
{
public:
bool eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == myLightEvent::type())
{
//"I don't wanna filter MyEventType";
return false;
}
return QObject::eventFilter(watched,event);
}
};
#endif // MYEVENT_H
myevent.cpp文件:
#include "myevent.h"
QEvent::Type myLightEvent::lightEventType = QEvent::None;
lightDPS.h中的大概内容:
class lightDPS : public QObject
{
Q_OBJECT
public:
bool event(QEvent *event);//重写event事件
}
lightDPS.cpp中的内容:
bool lightDPS::event(QEvent *event)
{
if(event->type() == myLightEvent::type())
{
//qDebug()<<"event() is dispathing MyEvent";
myLightEvent *lightEvent = static_cast<myLightEvent *>(event);
openLight(lightEvent->getLightAction());//开关灯的处理操作
event->accept();//接受事件,不再转发
if((myLightEvent*)event->isAccepted())
{
qDebug()<<"The event has been handled!";
return true;
}
}
return QObject::event(event);//非本对象处理的事件,返回给父对象处理
}
在业务流程中的调用,比如某个cpp中:
myLightEvent* mylightevent = new myLightEvent();//QT框架自动释放内存
mylightevent->setLightAction(lightDPS::OPEN_FILL);
QCoreApplication::postEvent(lightDPS::GetInstance(),mylightevent);