自定义摇杆

自定义摇杆

今天做项目的时候,接到一个需求,需要做一个摇杆去控制物体的移动,功能还是挺复杂的

1.功能:

  1. 点击内圈发送一次对应的方向的信号
  2. 松开鼠标的时候如果在内圈就发送结束信号(第一第二点总结起来就是按下跑,松开停)
  3. 松开的时候如果鼠标位置在外圈,就不发送结束信号,一直跑
  4. 点击结束按钮或者内圈范围都会发送信号

直接上图

原始状态:

持续行走状态:

2.代码

DirectionalControl.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
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
#ifndef DIRECTIONALCONTROL_H
#define DIRECTIONALCONTROL_H

#include <QWidget>
#include <QMouseEvent>
#include <QPainter>
#include <QPushButton>
#include <QCheckBox>
#include <QPointF>
#include <QDebug>

class DirectionalControl : public QWidget {
Q_OBJECT

public:
enum DirectionButton
{
UpButton,
DownButton,
LeftButton,
RightButton,
StopButton
};
explicit DirectionalControl(QWidget* parent = nullptr);
void resetDragPntPos();
public slots:
void sendDirectionChanged();

signals:
void directionChanged(double angle); // 信号:方向改变
void startMove();
void stopMove();
void handleClick();

protected:
void paintEvent(QPaintEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void updateDragPntDirection();
void keyReleaseEvent(QKeyEvent* event) override;

void keyPressEvent(QKeyEvent* event)override;

private:
const int outerRadius = 80; // 外圈半径
const int innerRadius = 45; // 内圈半径
QPointF center; // 中心点
QPointF dragPoint; // 当前拖动点
bool isDragging = false; // 是否正在拖动
double m_angle;
bool m_moving = false;

QPushButton* stopButton; //按钮


QTimer* m_timer; //定时器,控制angleChange()发送频率

bool isInsideOuterCircle(const QPointF& point);
bool isInsideInnerCircle(const QPointF& point);
void calculateDirection(); // 计算当前方向
void setupButtons(); // 初始化按钮布局
};

#endif // DIRECTIONALCONTROL_H

DirectionalControl.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#include "DirectionalControl.h"
#include "corecrt_math_defines.h"
#include <QtMath>
#include <QTimer>

DirectionalControl::DirectionalControl(QWidget* parent)
: QWidget(parent), center(100, 100) {

setFixedSize(200, 200);
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
setAttribute(Qt::WA_TranslucentBackground);
setFocusPolicy(Qt::StrongFocus);
//this->setCursor(Qt::CursorShape::PointingHandCursor);
m_timer = new QTimer(this);
dragPoint.setX(center.x());
dragPoint.setY(center.y());

QSize size = this->size();
setupButtons();

QFile file(":/qss/resources/qss/DirectionControl.qss");
QByteArray style;
if (file.open(QIODevice::ReadOnly))
{
style += file.readAll();
file.close();
}
setStyleSheet(style);
}

void DirectionalControl::resetDragPntPos()
{
dragPoint.setX(center.x());
dragPoint.setY(center.y());
update();
}

void DirectionalControl::sendDirectionChanged()
{
emit directionChanged(m_angle);
}



void DirectionalControl::setupButtons() {
// 中心按钮:开始/暂停
stopButton = new QPushButton(this);
stopButton->move(90, 90);
stopButton->setObjectName("stopButton");
connect(stopButton, &QPushButton::clicked, [this]() {
emit stopMove();
m_moving = false;
dragPoint.setX(center.x());
dragPoint.setY(center.y());
stopButton->hide();
update();
});
stopButton->hide();
}

void DirectionalControl::paintEvent(QPaintEvent* event) {
Q_UNUSED(event);

QPainter painter(this);
// 抗锯齿
painter.setRenderHint(QPainter::Antialiasing, true);



// 无边框,直接刷色
painter.setPen(Qt::NoPen);

const QColor outerCircleColor(200, 220, 255, 200); // 外圈颜色
const QColor innerCircleColor(249, 249, 249, 150); // 内圈颜色
const int centerDotRadius = 3; // 中心点半径
const int dragRadius = 15; // 拖动点半径

// 绘制外圈
painter.setBrush(outerCircleColor);
painter.drawEllipse(center, outerRadius, outerRadius);

//绘制内内圈
painter.setPen(QPen(QColor(255, 255, 255, 150), 3));//外边框
painter.setBrush(innerCircleColor);
painter.drawEllipse(center, dragRadius, dragRadius);

// 绘制内圈
painter.setPen(QPen(QColor(255, 255, 255, 150), 3));//外边框
painter.setBrush(innerCircleColor);
painter.drawEllipse(center, innerRadius, innerRadius);
// 确保 dragPoint 不进入内圈且不超出外圈
double dx = dragPoint.x() - center.x();
double dy = dragPoint.y() - center.y();
double distance = std::sqrt(dx * dx + dy * dy);

// 如果 dragPoint 超出了外圈,修正到外圈边缘
if (distance > outerRadius) {
double scale = outerRadius / distance;
dragPoint.setX(center.x() + dx * scale);
dragPoint.setY(center.y() + dy * scale);
}

painter.setPen(QPen(QColor(255, 255, 255)));
QFont font("Arial", 20, QFont::Bold);
// 设置画笔的字体
painter.setFont(font);

painter.drawText(87, 50, "W");
painter.drawText(28, 110, "A");
painter.drawText(90, 172, "S");
painter.drawText(152, 110, "D");
// 设置画刷颜色为白色并绘制拖动点
painter.setPen(Qt::NoPen);
painter.setBrush(Qt::white);
painter.drawEllipse(dragPoint, dragRadius, dragRadius);

// 在拖动点的中心绘制中心点
painter.setPen(QPen(QColor(0, 117, 255), 5));
painter.setBrush(QColor(0, 117, 255));
painter.drawEllipse(dragPoint, centerDotRadius, centerDotRadius);


}


void DirectionalControl::mousePressEvent(QMouseEvent* event) {
QPointF pos = event->pos();
//if (isInsideOuterCircle(pos) && isInsideInnerCircle(pos)) {
isDragging = true;
dragPoint = pos;
emit startMove();
m_moving = true;
calculateDirection();
sendDirectionChanged();
// 限制拖动点到外圈的范围
double dx = pos.x() - center.x();
double dy = pos.y() - center.y();
double distance = std::sqrt(dx * dx + dy * dy);

if (distance < innerRadius) {
emit handleClick();
}
m_timer->start(1000);
connect(m_timer, &QTimer::timeout, this, &DirectionalControl::sendDirectionChanged, Qt::ConnectionType(Qt::AutoConnection | Qt::UniqueConnection));
update();
//}
}

void DirectionalControl::mouseMoveEvent(QMouseEvent* event) {
if (isDragging) {
QPointF pos = event->pos();

// 限制拖动点到外圈的范围
double dx = pos.x() - center.x();
double dy = pos.y() - center.y();
double distance = std::sqrt(dx * dx + dy * dy);

if (distance > outerRadius) {
// 将拖动点限制在外圈的边界
double scale = outerRadius / distance;
dragPoint.setX(center.x() + dx * scale);
dragPoint.setY(center.y() + dy * scale);
}
/*else if (distance > innerRadius)
{
dragPoint.setX(center.x());
dragPoint.setY(center.y());
}*/
else {
dragPoint = pos;
}

calculateDirection();
update();
}
}

void DirectionalControl::mouseReleaseEvent(QMouseEvent* event) {
Q_UNUSED(event);
isDragging = false;
// TODO 点击内圈跑一步,点击外圈持续跑
// 释放时恢复到中心
// dragPoint = center;

QPointF pos = event->pos();

// 限制拖动点到外圈的范围
double dx = pos.x() - center.x();
double dy = pos.y() - center.y();
double distance = std::sqrt(dx * dx + dy * dy);

if (distance > innerRadius) {
// 将拖动点限制在外圈的边界
double distanceFromCenter = (outerRadius + innerRadius) / 2;
dragPoint.setX(center.x() +
distanceFromCenter * std::cos(qDegreesToRadians(m_angle)));
dragPoint.setY(center.y() -
distanceFromCenter * std::sin(qDegreesToRadians(m_angle)));
stopButton->show();
}
else if (distance < innerRadius)//拖动点释放前在内圈,就停止
{
calculateDirection();
dragPoint.setX(center.x());
dragPoint.setY(center.y());
stopButton->hide();
emit stopMove();
m_moving = false;
}
/*else {
dragPoint = pos;
}*/
/*double distanceFromCenter = (outerRadius + innerRadius) / 2;
dragPoint.setX(center.x() +
distanceFromCenter * std::cos(qDegreesToRadians(m_angle)));
dragPoint.setY(center.y() -
distanceFromCenter * std::sin(qDegreesToRadians(m_angle)));*/
m_timer->stop();
update();
}
void DirectionalControl::updateDragPntDirection()
{
double distanceFromCenter = (outerRadius + innerRadius) / 2;
dragPoint.setX(center.x() + distanceFromCenter * std::cos(qDegreesToRadians(m_angle)));
dragPoint.setY(center.y() - distanceFromCenter * std::sin(qDegreesToRadians(m_angle)));
update();
}
void DirectionalControl::keyPressEvent(QKeyEvent* event)
{
QWidget::keyPressEvent(event);

/*
* 防止重复触发按键,这是官方文档的描述
* bool QKeyEvent::isAutoRepeat() const
* Returns true if this event comes from an auto-repeating key;
* returns false if it comes from an initial key press.
* Note that if the event is a multiple-key compressed event that is partly due to auto-repeat,
* this function could return either true or false indeterminately.
*
*/
if (event->isAutoRepeat()) {
return;
}

switch (event->key()) {
case Qt::Key_W:
m_angle = 90;
sendDirectionChanged();
emit handleClick();
emit startMove();
stopButton->show();
m_moving = true;
updateDragPntDirection();
break;
case Qt::Key_A:
m_angle = 180;
sendDirectionChanged();
emit handleClick();
emit startMove();
stopButton->show();
m_moving = true;
updateDragPntDirection();
break;
case Qt::Key_S:
m_angle = 270;
sendDirectionChanged();
emit handleClick();
emit startMove();
stopButton->show();
m_moving = true;
updateDragPntDirection();
break;
case Qt::Key_D:
m_angle = 0;
sendDirectionChanged();
emit handleClick();
emit startMove();
stopButton->show();
m_moving = true;
updateDragPntDirection();
break;
default:
break;
}
// 标记事件为已处理
event->accept();
}

void DirectionalControl::keyReleaseEvent(QKeyEvent* event)
{
QWidget::keyReleaseEvent(event);

// 只处理非自动重复的松键事件
if (event->isAutoRepeat()) {
return;
}

switch (event->key()) {
case Qt::Key_W:
emit stopMove();
m_moving = false;
resetDragPntPos();
stopButton->hide();
break;
case Qt::Key_A:
emit stopMove();
m_moving = false;
resetDragPntPos();
stopButton->hide();
break;
case Qt::Key_S:
emit stopMove();
m_moving = false;
resetDragPntPos();
stopButton->hide();
break;
case Qt::Key_D:
emit stopMove();
m_moving = false;
resetDragPntPos();
stopButton->hide();
break;
case Qt::Key_Space:
emit stopMove();
m_moving = false;
resetDragPntPos();
stopButton->hide();
break;
default:
break;
}

// 标记事件为已处理
event->accept();
}
bool DirectionalControl::isInsideOuterCircle(const QPointF& point) {
double dx = point.x() - center.x();
double dy = point.y() - center.y();
return std::sqrt(dx * dx + dy * dy) <= outerRadius;
}

bool DirectionalControl::isInsideInnerCircle(const QPointF& point) {
double dx = point.x() - center.x();
double dy = point.y() - center.y();
return std::sqrt(dx * dx + dy * dy) <= innerRadius;
}

void DirectionalControl::calculateDirection() {
double dx = dragPoint.x() - center.x();
// Y 轴正方向向下,所以取反
double dy = center.y() - dragPoint.y();
double angle = std::atan2(dy, dx) * (180.0 / M_PI);
// 保证角度为 0-360 度
if (angle < 0) {
angle += 360.0;
}
m_angle = angle;

}