Widget.h:
#ifndef WIDGET_H #define WIDGET_H #include<QWidget> #include<QMouseEvent> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); void mousePressEvent(QMouseEvent* e); void mouseReleaseEvent(QMouseEvent* e); void mouseMoveEvent(QMouseEvent* e); }; #endif // WIDGET_H
Widget.cpp:
#include "widget.h" #include<QDebug> Widget::Widget(QWidget *parent) : QWidget(parent) { this->setMouseTracking(true);//设置鼠标移动事件不需要按下也能促发 } void Widget::mousePressEvent(QMouseEvent* e) { switch(e->button()) { case Qt::LeftButton: qDebug()<<"leftbutton is pressed"<<endl; break; case Qt::RightButton: qDebug()<<"rightbutton is pressed"<<endl; break; case Qt::MidButton: qDebug()<<"midbutton is pressed"<<endl; break; default: break; } } void Widget::mouseReleaseEvent(QMouseEvent* e) { switch(e->button()) { case Qt::LeftButton: qDebug()<<"leftbutton is released"<<endl; break; case Qt::RightButton: qDebug()<<"rightbutton is released"<<endl; break; case Qt::MidButton: qDebug()<<"midbutton is released"<<endl; break; default: break; } } void Widget::mouseMoveEvent(QMouseEvent* e) { qDebug()<<e->pos()<<endl; } Widget::~Widget() { }
main.cpp:
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
效果: