原创
Qt5.9的鼠标事件:进入QWidget界面事件、离开QWidget界面事件、摁住鼠标事件
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
</div>
<!--一个博主专栏付费入口-->
<!--一个博主专栏付费入口结束-->
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-833878f763.css">
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-833878f763.css">
<div class="htmledit_views" id="content_views">
<p>本文主要总结用Qt5.9实现常用鼠标事件,包括进入QWidget界面事件、离开QWidget界面事件、摁住鼠标事件。实现上面三个事件,只需要改写虚函数enterEvent(QEvent *),leaveEvent(QEvent *),mouseMoveEvent(QMouseEvent * event)就可以实现。</p>
下面是具体的实例步骤:
1.1新建一个widget工程,不要勾选ui界面。然后分别在widget.h,widget.cpp,main.cpp分别添加如下代码。
widget.h
-
#ifndef WIDGET_H
-
#define WIDGET_H
-
-
#include <QWidget>
-
#include <QPushButton>
-
#include <QEvent>
-
#include <QMouseEvent>
-
-
class Widget :
public QWidget
-
{
-
Q_OBJECT
-
-
public:
-
Widget(QWidget *parent =
0);
-
~Widget();
-
-
protected:
-
void enterEvent(QEvent *);
//进入QWidget瞬间事件
-
void leaveEvent(QEvent *);
//离开QWidget瞬间事件
-
void mouseMoveEvent(QMouseEvent * event);
//摁住鼠标事件
-
-
private:
-
void setupUI();
-
QPushButton *button;
-
};
-
-
#endif // WIDGET_H
widget.cpp
-
#include "widget.h"
-
#include <QVBoxLayout>
-
#include <QDebug>
-
-
Widget::Widget(QWidget *parent)
-
: QWidget(parent)
-
{
-
//窗口UI界面初始化
-
setupUI();
-
}
-
-
Widget::~Widget()
-
{
-
}
-
-
void Widget::enterEvent(QEvent *)
-
{
-
if(button->geometry().contains(
this->mapFromGlobal(QCursor::pos())))
-
qDebug()<<
"123";
-
qDebug()<<tr(
"鼠标进入主界面事件");
-
}
-
-
void Widget::leaveEvent(QEvent *)
-
{
-
qDebug()<<tr(
"鼠标离开主界面事件");
-
}
-
-
void Widget::mouseMoveEvent(QMouseEvent * event)
-
{
-
qDebug()<<tr(
"%1,%2").arg(event->pos().x()).arg(event->pos().y());
-
}
-
-
void Widget::setupUI()
-
{
-
button =
new QPushButton(
"button");
-
-
QVBoxLayout *mainLayout =
new QVBoxLayout();
-
mainLayout->addWidget(button);
-
mainLayout->addStretch();
-
this->setLayout(mainLayout);
-
}
main.cpp
-
#include "widget.h"
-
#include <QApplication>
-
-
int main(int argc, char *argv[])
-
{
-
QApplication a(argc, argv);
-
Widget w;
-
w.resize(
960,
640);
-
w.setWindowTitle(QString::fromUtf8(
"鼠标事件:进入界面、离开界面、摁住鼠标"));
-
w.show();
-
-
return a.exec();
-
}
1.2程序构建和运行后,结果如下图所示:
参考内容:
https://blog.csdn.net/u012997311/article/details/53027521(主要参考:enterEvent(),leaveEvent())
https://zhidao.baidu.com/question/367842714682272084.html(主要参考:mouseMoveEvent())