QT之鼠标事件
Posted sunshine-gzw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QT之鼠标事件相关的知识,希望对你有一定的参考价值。
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(); }
效果:
以上是关于QT之鼠标事件的主要内容,如果未能解决你的问题,请参考以下文章