QT 窗口拖拽移动实现

我们知道,要实现窗口移动可以直接鼠标点住窗口的标题栏实现拖拽移动,这是窗口默认的行为,在QT中的事件响应函数为moveEvent。

但是现实中经常需要鼠标点住窗口客户区域实现窗口的拖拽移动,代码实现如下:

Widget.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 
#ifndef  WIDGET_H
#define  WIDGET_H

#include  <QWidget>

class  QMouseEvent;
class  Widget :  public  QWidget
{
    Q_OBJECT

public :
    Widget(QWidget *parent = 
0 );
    ~Widget();

protected :
    
//拖拽窗口
     void  mousePressEvent(QMouseEvent *event);
    
void  mouseMoveEvent(QMouseEvent *event);
    
void  mouseReleaseEvent(QMouseEvent *event);

private :
    
bool         m_bDrag;
    QPoint      mouseStartPoint;
    QPoint      windowTopLeftPoint;
};

#endif   // WIDGET_H
Widget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 
#include   "Widget.h"
#include  <QMouseEvent>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , m_bDrag(
false )
{
    setWindowTitle(
"窗口拖拽移动" );
    setFixedSize(640, 480);
}

Widget::~Widget()
{

}

/* QPoint QMouseEvent::pos() const
    Returns the position of the mouse cursor, relative to the widget that received the event.
    If you move the widget as a result of the mouse event, use the global position returned by globalPos() to avoid a shaking motion.
 */


//拖拽操作
void  Widget::mousePressEvent(QMouseEvent *event)
{
    
if (event->button() == Qt::LeftButton)
    {
        m_bDrag = 
true ;
        
//获得鼠标的初始位置
        mouseStartPoint = event->globalPos();
        
//mouseStartPoint = event->pos();
         //获得窗口的初始位置
        windowTopLeftPoint =  this ->frameGeometry().topLeft();
    }
}

void  Widget::mouseMoveEvent(QMouseEvent *event)
{
    
if (m_bDrag)
    {
        
//获得鼠标移动的距离
        QPoint distance = event->globalPos() - mouseStartPoint;
        
//QPoint distance = event->pos() - mouseStartPoint;
         //改变窗口的位置
         this ->move(windowTopLeftPoint + distance);
    }
}

void  Widget::mouseReleaseEvent(QMouseEvent *event)
{
    
if (event->button() == Qt::LeftButton)
    {
        m_bDrag = 
false ;
    }
}

需要注意的一点:一般定位鼠标坐标使用的是event->pos()和event->globalPos()两个函数,

event->globalPos()获取的鼠标位置是鼠标偏离电脑屏幕左上角(x=0,y=0)的位置;

event->pos()获取的位置是主窗口(widget窗口)左上角(边框的左上角,左上角)相对于电脑屏幕的左上角的(x=0,y=0)偏移位置

一般不采用前者,使用前者,拖动准确性较低且会产生抖动

转载于:https://www.cnblogs.com/MakeView660/p/10619334.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值