我们知道,要实现窗口移动可以直接鼠标点住窗口的标题栏实现拖拽移动,这是窗口默认的行为,在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)偏移位置
一般不采用前者,使用前者,拖动准确性较低且会产生抖动。

希望大家能把自己的所学和他人一起分享,不要去鄙视别人索取时的贪婪,因为最应该被鄙视的是不肯分享时的吝啬。