Qt的事件会汇聚到 QCoreApplication::notify ,然后再分发出去,因此整个程序的消息可以在此过滤,继承 QCoreApplication 重写 QCoreApplication::notify 即可:
class MyApplication : public QApplication
{
public:
MyApplication(int & argc, char ** argv):QApplication(argc, argv){};
virtual bool notify(QObject * obj, QEvent * event)
{
//qDebug()<<__PRETTY_FUNCTION__<<obj<<event;
if(event->type() == QMouseEvent::MouseButtonPress)
{
qDebug()<<__PRETTY_FUNCTION__<<obj<<event;
}
return QApplication::notify(obj,event);
}
};
使用时在 main 中将 Application 换成 MyApplication 即可:
MyApplication app(argc, argv);
效果:
大部分情况下,继承 QObject,重写 virtual bool eventFilter(QObject , QEvent ); 就可以解决问题了。