好比鼠標點擊消息:QApplication先獲取消息--->具體應該處理的窗口::event()---> event()根據消息類型來調用具體的虛函數函數
1)能夠重載具體的虛函數,來實現對消息的響應
2)能夠重載event函數,用來處理或者截取消息。可是重寫玩event以後,要把事件從新傳遞給具體應該處理的窗口,而後這個窗口又傳遞給QApplication。例如:this
#include <QEvent> bool Widget::event(QEvent *event) { return QWidget::event(event); }
event至關於一個開關,能夠在這個開關裏面關閉某個消息機制:好比若是檢測到鼠標左鍵按下時,直接返回。code
#include <QEvent> bool Widget::event(QEvent *event) { if(ev->type() == QEvent::MouseButtonPress) return true; return QWidget::event(event); }
二、重寫具體的虛函數以實現對事件的處理,好比鼠標按下事件:事件
#include <QMouseEvent> #include <QDebug> void Widget::mousePressEvent(QMouseEvent *event) { QPoint pt = event->pos(); //獲取鼠標按下的位置 qDebug() << pt; if(ev->button() == Qt::LeftButton) { if(ev->modifiers() == Qt::ControlModifier) { // handle with Control; return; } // handle2 without control; } }
鼠標移動事件:get
//構造函數中添加: this->setMouseTracking(true); //不須要按下只要鼠標在widget上移動就能感應 //若是不將setMouseTracking設置爲true,那麼只有shu鼠標按下而且移動纔能有mouseMoveEvent事件發生 void Widget::mouseMoveEvent(QMouseEvent *) { static int i=0; qDebug() << "mouse move"<< i++; }
鼠標事件默認狀況下只能由一個窗口處理,好比若是在widget上放置了一個按鈕,當鼠標在按鈕上移動時,mouseMoveEvent不能感應,應爲mouseMoveEvent是Widget的,不是Button的it