QT是事件驅動的,監聽事件天然也是一個重點啦。首先是監聽鼠標事件。函數
新建項目,基於mainwindow頭文件:this
#ifndef MOUSEEVENT_H #define MOUSEEVENT_H #include <QMainWindow> #include <QLabel> #include <QStatusBar> #include <QMouseEvent> class MouseEvent : public QMainWindow { Q_OBJECT public: MouseEvent(QWidget *parent = 0); ~MouseEvent(); protected: void mousePressEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e); void mouseDoubleClickEvent(QMouseEvent *); private: QLabel *statusLabel; QLabel *mousePosLabel; }; #endif // MOUSEEVENT_H
主要代碼:spa
#include "mouseevent.h" MouseEvent::MouseEvent(QWidget *parent) : QMainWindow(parent) { setWindowTitle(tr("鼠標事件")); statusLabel=new QLabel; statusLabel->setText(tr("當前位置:")); statusLabel->setFixedWidth(100); mousePosLabel=new QLabel; mousePosLabel->setText(tr("")); mousePosLabel->setFixedWidth(100); statusBar()->addPermanentWidget(statusLabel); statusBar()->addPermanentWidget(mousePosLabel); this->setMouseTracking(true); resize(400,200); } MouseEvent::~MouseEvent() { } void MouseEvent::mousePressEvent(QMouseEvent *e) { QString str="("+QString::number(e->x())+","+QString::number (e->y())+")"; if(e->button()==Qt::LeftButton) { statusBar()->showMessage(tr("左鍵")+str); } if(e->button()==Qt::RightButton) { statusBar()->showMessage(tr("右鍵")+str); } if(e->button()==Qt::MidButton) { statusBar()->showMessage(tr("滾輪")+str); } } void MouseEvent::mouseMoveEvent(QMouseEvent *e) { mousePosLabel->setText("("+QString::number(e->x())+","+QString::number(e->y())+")"); } void MouseEvent::mouseReleaseEvent(QMouseEvent *e) { QString str="("+QString::number(e->x())+","+QString::number(e->y())+")"; statusBar()->showMessage(tr("釋放位置:")+str,3000); } void MouseEvent::mouseDoubleClickEvent(QMouseEvent *) { }
這裏的 setMouseTracking()函數,是用來決定是否 實時追蹤鼠標,默認的是false。但是咱們須要實時得到鼠標的位置,所以須要設置誒true。 code
運行效果:事件