QT自定义事件的一个例子

QT自定义事件的一个例子

 在QT中事件分为系统事件和自定义事件,可以看到QT跟MFC的消息很相似,MFC中消息也分为系统消息和用户自定的消息,下面来说明一下QT中自定义事件的实现方法。

1>自定义一个从QEvent派生的的类如,TestEvent,实现如下:

testEvent.h文件

  1. #ifndef TESTEVENT_H 
  2. #define TESTEVENT_H  
  3. #include <QEvent>  
  4. class TestEvent : public QEvent 
  5. public
  6.     TestEvent(); 
  7.  
  8. public
  9.     static const Type EventType; 
  10. }; 
  11.  
  12. #endif // TESTEVENT_H 

testEvent.cpp文件

  1. #include "testevent.h"  
  2. const QEvent::Type TestEvent::EventType = (QEvent::Type)QEvent::registerEventType(QEvent::User+100); 
  3. TestEvent::TestEvent()  : QEvent(EventType) 

这样一个自定义的事件就完成了,有关事件的Type取值的问题请参考相关的资料,网上很多,比如

http://www.devbean.info/2012/10/qt-study-road-2-custom-event/

2>添加发送事件的代码

在main.cpp中如下:

  1. #include "mainwindow.h" 
  2. #include <QApplication> 
  3. #include "testevent.h"  
  4. int main(int argc, char *argv[]) 
  5.     QApplication a(argc, argv); 
  6.     MainWindow w; 
  7.     w.show(); 
  8.  
  9.     TestEvent tEvent; 
  10.     a.sendEvent(&w, &tEvent); 
  11.     return a.exec(); 

这样应用程序就将tEvent所代表的事件发送给了w所代表的MainWindow。

3>添加事件处理代码:

主要是重写event函数

mainwindow.h文件中:

  1. #ifndef MAINWINDOW_H 
  2. #define MAINWINDOW_H 
  3. #include <QMainWindow> 
  4. class TestEvent; 
  5. class MainWindow : public QMainWindow 
  6.     Q_OBJECT      
  7. public
  8.     MainWindow(QWidget *parent = 0); 
  9.     ~MainWindow();  
  10. protected
  11.     bool event(QEvent* event); 
  12.     void processTestEvent(TestEvent* event); 
  13. }; 
  14.  
  15. #endif // MAINWINDOW_H 

mainwindow.cpp文件中:

  1. #include "mainwindow.h" 
  2. #include "testevent.h" 
  3. #include <QDebug>  
  4. MainWindow::MainWindow(QWidget *parent) 
  5.     : QMainWindow(parent) 
  6.  
  7. MainWindow::~MainWindow() 
  8.      
  9.  
  10. bool MainWindow::event(QEvent* event) 
  11.     if(event->type() == TestEvent::EventType) 
  12.     { 
  13.         qDebug()<<"event() is dispathing TestEvent"
  14.  
  15.         TestEvent* testEvent = static_cast<TestEvent* >(event); 
  16.         processTestEvent(testEvent);  
  17.         if(testEvent->isAccepted()) 
  18.         { 
  19.             qDebug()<<"The testEvent has been handled!"
  20.             return true
  21.         } 
  22.     }  
  23.     return QObject::event(event); 
  24.  
  25.  void MainWindow::processTestEvent(TestEvent* event) 
  26.  { 
  27.      qDebug("processTestEvent"); 
  28.      event->accept(); 
  29.  } 

4>程序运行输出:

完。

猜你喜欢

转载自blog.csdn.net/komtao520/article/details/81535984