在最近的一个项目中,利用到了别人给的一个框架代码,但是短时间内无法深究其窗口间的层次关系,因此对不同窗口类的事件改写就很棘手,在大佬介绍下,采用了notificy函数,该函数可以捕获该程序的所有事件,因此我们可以通过debug信息获知该类窗口的事件。
具体实现如下:
- 在Qt中新建一个类
.h如下
#ifndef MYAPPLICATION_H
#define MYAPPLICATION_H
#include <QApplication>
class myApplication :public QApplication //此处需继承QApplication
{
public:
myApplication(int argc, char *argv[]);
protected:
virtual bool notify(QObject *obj, QEvent *event); //对该类重写notify事件
};
#endif // MYAPPLICATION_H
.cpp如下:
#include "myapplication.h"
myApplication::myApplication(int argc, char *argv[]):QApplication(argc, argv)
{
}
bool myApplication::notify(QObject *obj, QEvent *event)
{
if(event->type() == QMouseEvent::MouseButtonPress)//可以设置此处的event->type()来捕获不同类型的event事件
{
qDebug()<<__PRETTY_FUNCTION__<<obj<<event;
}
else if(event->type() == QEvent::NonClientAreaMouseButtonRelease)
{
qDebug()<<__PRETTY_FUNCTION__<<obj<<event;//__FUNCTION__ 函数,提供类名和函数名称的输出
}
return QApplication::notify(obj,event);
}
main函数下,
#include "mainwindow.h"
#include <QApplication>
#include "myapplication.h"
int main(int argc, char *argv[])
{
myApplication a(argc, argv); //注意此处是用myApplication构造 不是QApplication
MainWindow w;
w.show();
return a.exec();
}
执行结果如下:
因此通过对事件的捕获,我们就得知了对窗口的事件,需要我们重写哪个类的事件函数。