QT中的鼠标移动事件


关注

QMouseEvent类
其中还有press事件、release事件、move事件.......

为了练习move事件,做了一个按钮跟随鼠标小程序
首先我们可以查阅文档:
mouseMoveEvent事件,
[virtual protected] void QWindow::mouseMoveEvent(QMouseEvent *ev);
这是一个虚函数,可以用来重载的
我们就在自己的函数中

 

 

 重写虚函数:

 pbt.move(event->x(),event->y());  //设置按钮跟随坐标

 

在按钮创建需要在类中进行.建立成员函数的方式创建

 

 

 设置PushButton

 

 

 

    //直接打开鼠标事件
    setMouseTracking(true);
-------------------------------------------------------------------------------------------------------
#include "widget.h"
#include "ui_widget.h"
 
#include <QMouseEvent>
#include <QDebug>
 
 
int i = 0;
int j  =0 ;
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
 
    resize(800,600);
 
    //直接打开鼠标事件
    setMouseTracking(true);


 
 
    pbt.setParent(this);
    pbt.setText("欢迎");
 
    pbt.move(350,300);
    pbt.resize(80,50);
 
}
 
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    QString str = QString("鼠标移动了  x = %1 y =%2 ").arg(event->x()).arg(event->y());
    qDebug() <<str;
 
        //按钮移动
    pbt.move(event->x(),event->y());
}
 
Widget::~Widget()
{
    delete ui;
}

----------------

 

 

还有

event->button() ==Qt::LeftButton;   //左键;判断按键
event->buttons()   &Qt::LeftButton;   //判断联合按钮


----------------------------------------------------------------------------
重写void mousePressEvent
重写void mouseReleaseEvent
这种属于拦截事件操作,为了不影响其他按钮写完要return
return QPushButton::mousePressEvent(e);



 






免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM