Qt实现用鼠标拖拽对话框

Qt实现用鼠标拖拽对话框

在QWidget类中定义了两个函数

void mousePressEvent(QMouseEvent *);
//鼠标点击时执行的槽函数
void mouseMoveEvent(QMouseEvent *);
//鼠标移动时执行的槽函数

继承自QWidget的类中可以重定义这两个函数,从而实现拖拽对话框的操作
头文件

#include<qwidget.h>
#include<QMouseEvent>
class Dlg : public QWidget
{
Q_OBJECT

public:
Dlg(QWidget *parent = 0);
public slots:
void mouseMoveEvent(QMouseEvent *);
void mousePressEvent(QMouseEvent *);
private:
QPoint dragPoint;//记录坐标
};

源文件

#include"dlg.h"
Dlg::Dlg(QWidget *parent): QWidget(parent){
//自行实现
}
void Dlg::mousePressEvent(QMouseEvent *event){
if (event->button() == Qt::LeftButton){
    dragPoint = event->globalPos() - frameGeometry().topLeft();//记录鼠标点坐标和对话框左上角坐标的差值
    event->accept();
    }
}
void Dlg::mouseMoveEvent(QMouseEvent *event){
    if (event->buttons()&Qt::LeftButton){
    move(event->globalPos() - dragPoint);//move的参数是对话框左上角的坐标,根据差值和当前鼠标点计算出移动的对话框左上角的坐标值
    event->accept();
    }
}

注意

event->buttons()&Qt::LeftButton

改成

event->button()==Qt::LeftButton

将没有效果

button()和buttons()差别

Qt::MouseButton QMouseEvent::button() const

Returns the button that caused the event.
Note that the returned value is always Qt::NoButton for mouse move events.
See also buttons() and Qt::MouseButton.


Qt::MouseButtons QMouseEvent::buttons() const

Returns the button state when the event was generated. The button state is a combination of Qt::LeftButton, Qt::RightButton, Qt::MidButton using the OR operator. For mouse move events, this is all buttons that are pressed down. For mouse press and double click events this includes the button that caused the event. For mouse release events this excludes the button that caused the event.
See also button() and Qt::MouseButton.

因为对于QMouseEvent::button()来说,鼠标移动的时候他的值恒为Qt::NoButton

Note that the returned value is always Qt::NoButton for mouse move events.
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值