forked from feiyangqingyun/QWidgetDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmovewidget.cpp
84 lines (74 loc) · 2.71 KB
/
movewidget.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "movewidget.h"
#include "qevent.h"
#include "qdebug.h"
MoveWidget::MoveWidget(QObject *parent) : QObject(parent)
{
lastPoint = QPoint(0, 0);
pressed = false;
leftButton = false;
rightButton = false;
inControl = true;
widget = 0;
}
bool MoveWidget::eventFilter(QObject *watched, QEvent *event)
{
if (widget != 0 && watched == widget) {
QMouseEvent *mouseEvent = (QMouseEvent *)event;
if (mouseEvent->type() == QEvent::MouseButtonPress) {
//如果鼠标左键和鼠标右键都可以拖动
if (leftButton && rightButton) {
}
//如果限定了只能鼠标左键拖动则判断当前是否是鼠标左键,如果限定了只能鼠标右键拖动则判断当前是否是鼠标右键
else if ((leftButton && mouseEvent->button() != Qt::LeftButton) || (rightButton && mouseEvent->button() != Qt::RightButton)) {
return false;
}
//判断控件的区域是否包含了当前鼠标的坐标
if (widget->rect().contains(mouseEvent->pos())) {
lastPoint = mouseEvent->pos();
pressed = true;
}
} else if (mouseEvent->type() == QEvent::MouseMove && pressed) {
//计算坐标偏移值,调用move函数移动过去
int offsetX = mouseEvent->pos().x() - lastPoint.x();
int offsetY = mouseEvent->pos().y() - lastPoint.y();
int x = widget->x() + offsetX;
int y = widget->y() + offsetY;
if (inControl) {
//可以自行调整限定在容器中的范围,这里默认保留20个像素在里面
int offset = 20;
bool xyOut = (x + widget->width() < offset || y + widget->height() < offset);
bool whOut = false;
QWidget *w = (QWidget *)widget->parent();
if (w != 0) {
whOut = (w->width() - x < offset || w->height() - y < offset);
}
if (xyOut || whOut) {
return false;
}
}
widget->move(x, y);
} else if (mouseEvent->type() == QEvent::MouseButtonRelease && pressed) {
pressed = false;
}
}
return QObject::eventFilter(watched, event);
}
void MoveWidget::setWidget(QWidget *widget)
{
if (this->widget == 0) {
this->widget = widget;
this->widget->installEventFilter(this);
}
}
void MoveWidget::setLeftButton(bool leftButton)
{
this->leftButton = leftButton;
}
void MoveWidget::setRightButton(bool rightButton)
{
this->rightButton = rightButton;
}
void MoveWidget::setInControl(bool inControl)
{
this->inControl = inControl;
}