Qt重写nativeEvent无响应问题的说明

虽然Qt事件对于系统的消息做了一些封装,但在实际过程中Qt封装的消息不满足我们,因此我们需要windos消息机制,在判断windows消息时,便要重写nativeEvent事件。(在Qt4中该函数为winEvent,在Qt5中改为nativeEvent)

Windows消息总结

https://www.cnblogs.com/Sunwayking/articles/2817580.html

重写nativeEvent具体实现步骤:

  • 在.h文件下声明重写
protected:
   virtual bool nativeEvent(const QByteArray &eventType, void *message, long *result);
  • 在.cpp文件下导入头文件
#include <windows.h>  
#include <windowsx.h>  //提供消息关键字的识别
  • 在.cpp文件下重写 nativeEvent
bool OpenGLWidget::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
     Q_UNUSED(eventType); 
     MSG *msg = static_cast<MSG*>(message);  //类型转换
     /*此处的结构也可用switch来代替*/
     if(msg->message ==WM_WINDOWPOSCHANGED )
     {
         dosomething...

         return false;  //返回值为false表示该事件还会继续向上传递,被其他捕获
     }
     else if(msg->message == WM_LBUTTONUP)
     {
         dosomething...

         return false;
     }

   return false;

}

问题说明:

在实现过程中,会出现事件无响应的情况,具体原因是,nativeEvent的重写的类,该类必须是窗口界面,才可以获得响应。

若是将customwidget加入到mainwindow页面中,则customwidget不会响应。

发布了11 篇原创文章 · 获赞 3 · 访问量 2367

猜你喜欢

转载自blog.csdn.net/weixin_42108411/article/details/95059894