Qt5.9的鼠标事件:进入QWidget界面事件、离开QWidget界面事件、摁住鼠标事件

本文主要总结用Qt5.9实现常用鼠标事件,包括进入QWidget界面事件、离开QWidget界面事件、摁住鼠标事件。实现上面三个事件,只需要改写虚函数enterEvent(QEvent *),leaveEvent(QEvent *),mouseMoveEvent(QMouseEvent * event)就可以实现。

下面是具体的实例步骤:

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())

 

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三公子Tjq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值