在QT场景视图中2D图形项Item的基类为QGraphicsItem,如果我们需要自定义Item则可以从其派生,然后重写boundingRect以及paint虚函数实现图形项的外边界定义以及内容绘制工作。如果需要将Qt基本的Widget组件加入到场景中,该框架为我们提供了QGraphicsWidget(QGraphicsProxyWidget)类,如果需要图形项具有信号槽的功能,该框架又提供了QGraphicsObject类,方便我们根据需要选择相关的类。

QgraphicsItem类提供了简单方便的setRotation方法传入旋转角度(-360,360)来直接控制图形项绕Z轴(垂直于屏幕的轴)的顺时针以及逆时针旋转,也可以通过更加综合性的QTransform类来实现。旋转的中心点则可以通过setTransformOriginPoint()方法来设定,默认是(0,0)坐标原点。

需要明白的是,对图形项的旋转实质上是对项坐标系的旋转,图形绘制的坐标相对于项坐标是不变的。

调用setRotation方法固然方便,但需要手动指定旋转的角度值,而实际的情况中,我们常常需要通过鼠标选中并移动来实现旋转,这就需要通过鼠标移动来不断计算正确的旋转角度值,这是重点,也是难点。

思路:

1) 确定旋转中心坐标:centerPoint(O)

2) 在mousePressEvent事件响应中获取按下时旋转控制点坐标:pressPoint(A)

3) 在mouseMoveEvent事件响应中获取当前移动点的坐标:movePoint(B)

4)      centerPoint、pressPoint、movePoint三点确定的旋转角度angle:角AOB

5)      在原始旋转角度rotation()基础上设置新的累积角度

setRotation(rotation() + angle);

难点:如何计算角AOB

inline qreal GetDegreeAngle(QVector2D vector2d) const

{

return fmod((atan2((qreal)vector2d.y(), (qreal)vector2d.x()) * AnglePerPI + 360.0), 360.0 );

}

C 语言里 double atan2(double y,double x) 返回的是原点至点(x,y)的方位角,即与 x 轴的夹角。返回值的单位为弧度,取值范围为(-π, π]。结果为正表示从 X 轴逆时针旋转的角度,结果为负表示从 X 轴顺时针旋转的角度。若要用度表示反正切值,请将结果再乘以 180/π。fmod是浮点数求余数运算,函数整体返回向量与+x轴的顺时针角度值。

测试代码:

仅供参考,如有错误,欢迎指正,欢迎改进帮助更加完善。

 C++ Code 
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
 
#ifndef ITEMBASE_H
#define ITEMBASE_H

#include <QGraphicsItem>
#include <QTime>
#include <QVector2D>
#include <cmath>

;
 / PI;

class QGraphicsScene;
class ItemBase : public QGraphicsItem
{
public:
     };

ItemBase(int size, int x, int y);
    ~ItemBase() override;

QRectF boundingRect() const override;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;

inline qreal GetDegreeAngle(QVector2D vector2d) const
    {
         );
    }

protected:
    ;
    void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
    void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override;
    void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
    void keyPressEvent(QKeyEvent *event) override;
    void wheelEvent(QGraphicsSceneWheelEvent *event) override;
    int type() const override;
    bool isInResizeArea(const QPointF &pos);
    bool isInRotateArea(const QPointF &pos);

static void duplicateSelectedItems(QGraphicsScene *scene);
    static void deleteSelectedItems(QGraphicsScene *scene);
    static void growSelectedItems(QGraphicsScene *scene);
    static void shrinkSelectedItems(QGraphicsScene *scene);

int         m_size;
    QTime       m_startTime;
    bool        m_isResizing;
    bool        m_isRotating;
};

#endif // ITEMBASE_H

#include "ItemBase.h"
#include <QStyleOptionGraphicsItem>
#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsEllipseItem>
#include <QMenu>
#include <QGraphicsSceneMouseEvent>
#include <QKeyEvent>
#include <qmath.h>
#include <GL/gl.h>
#include <QDebug>
#include <QRandomGenerator>

;
;

//============================================================================//
//                                  ItemBase                                  //
//============================================================================//

ItemBase::ItemBase(int size, int x, int y)
    : m_size(size)
    , m_isResizing(false)
    , m_isRotating(false)
{
    setFlag(QGraphicsItem::ItemIsMovable, true);
    setFlag(QGraphicsItem::ItemIsSelectable, true);
    setFlag(QGraphicsItem::ItemIsFocusable, true);
    setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
    setAcceptHoverEvents(true);
    setPos(x, y);
    m_startTime = QTime::currentTime();
}

ItemBase::~ItemBase()
{

}

QRectF ItemBase::boundingRect() const
{
    , m_size, m_size);
}

void ItemBase::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
{
    if (option->state & QStyle::State_Selected)
    {
        painter->setRenderHint(QPainter::Antialiasing, true);
        if (option->state & QStyle::State_HasFocus)
        {
            painter->setPen(Qt::yellow);
        }
        else
        {
            painter->setPen(Qt::white);
        }
        painter->drawRect(boundingRect());
        // resize contrl area...
);
        painter->drawLine(m_size / );
        painter->drawLine(m_size / );
        // rotate control point
        painter->setPen(Qt::blue);
        painter->drawLine();
        painter->setPen(QPen(Qt::blue, ));
        painter->drawPoint();

painter->setRenderHint(QPainter::Antialiasing, false);

}
    else
    {

}
}

void ItemBase::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    if (!isSelected() && scene())
    {
        scene()->clearSelection();
        setSelected(true);
    }

QMenu menu;
    QAction *delAction = menu.addAction("Delete");
    QAction *newAction = menu.addAction("New");
    QAction *growAction = menu.addAction("Grow");
    QAction *shrinkAction = menu.addAction("Shrink");

QAction *selectedAction = menu.exec(event->screenPos());

if (selectedAction == delAction)
        deleteSelectedItems(scene());
    else if (selectedAction == newAction)
        duplicateSelectedItems(scene());
    else if (selectedAction == growAction)
        growSelectedItems(scene());
    else if (selectedAction == shrinkAction)
        shrinkSelectedItems(scene());
}

void ItemBase::duplicateSelectedItems(QGraphicsScene *scene)
{
    if (!scene)
        return;

QList<QGraphicsItem *> selected;
    selected = scene->selectedItems();

foreach (QGraphicsItem *item, selected)
    {
        ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
        if (itemBase)
            scene->addItem(itemBase->createNew(itemBase->m_size,
                                               static_cast<int>(itemBase->pos().x()) + itemBase->m_size,
                                               static_cast<int>(itemBase->pos().y())));
    }
}

void ItemBase::deleteSelectedItems(QGraphicsScene *scene)
{
    if (!scene)
        return;

QList<QGraphicsItem *> selected;
    selected = scene->selectedItems();

foreach (QGraphicsItem *item, selected)
    {
        ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
        if (itemBase)
            delete itemBase;
    }
}

void ItemBase::growSelectedItems(QGraphicsScene *scene)
{
    if (!scene)
        return;

QList<QGraphicsItem *> selected;
    selected = scene->selectedItems();

foreach (QGraphicsItem *item, selected)
    {
        ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
        if (itemBase)
        {
            itemBase->prepareGeometryChange();
            itemBase->m_size *= ;
            if (itemBase->m_size > MAX_ITEM_SIZE)
                itemBase->m_size = MAX_ITEM_SIZE;
        }
    }
}

void ItemBase::shrinkSelectedItems(QGraphicsScene *scene)
{
    if (!scene)
        return;

QList<QGraphicsItem *> selected;
    selected = scene->selectedItems();

foreach (QGraphicsItem *item, selected)
    {
        ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
        if (itemBase)
        {
            itemBase->prepareGeometryChange();
            itemBase->m_size /= ;
            if (itemBase->m_size < MIN_ITEM_SIZE)
                itemBase->m_size = MIN_ITEM_SIZE;
        }
    }
}

void ItemBase::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    if (m_isResizing)
    {
         * event->pos().x());
         * event->pos().y());
        prepareGeometryChange();
        m_size = (dx > dy ? dx : dy);
        if (m_size < MIN_ITEM_SIZE)
            m_size = MIN_ITEM_SIZE;
        else if (m_size > MAX_ITEM_SIZE)
            m_size = MAX_ITEM_SIZE;
    }
    else if (m_isRotating)
    {
        QPointF cursorPos = event->pos();
        QVector2D vectorStart = QVector2D(QPointF());           // 起始向量
));                             // 结束向量
        // 计算起始向量和结束向量之间的角度
;
        qreal angleEnd = GetDegreeAngle(vectorEnd);
        qreal angleStart = GetDegreeAngle(vectorStart);
        angle = angleEnd - angleStart + rotation();
        )
        {
            )
            {
                angle -= ;
                ) break;
            }
        }
        )
        {
            )
            {
                angle += ;
                ) break;
            }
        }
        setRotation(angle);
    }
    else
    {
        QGraphicsItem::mouseMoveEvent(event);
    }
}

void ItemBase::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
    if (m_isResizing || (isInResizeArea(event->pos()) && isSelected()))
        setCursor(Qt::SizeFDiagCursor);
    else if ((isInRotateArea(event->pos()) && isSelected()))
    {
        QCursor *rotateCursor = new QCursor(QPixmap(":/rotate_handler.png"));
        setCursor(*rotateCursor);
    }
    else
        setCursor(Qt::ArrowCursor);
    QGraphicsItem::hoverMoveEvent(event);
}

void ItemBase::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    ;
    setZValue(z += );
    if (event->button() == Qt::LeftButton && isInResizeArea(event->pos()))
    {
        m_isResizing = true;
    }
    else if (event->button() == Qt::LeftButton && isInRotateArea(event->pos()))
    {
        m_isRotating = true;
    }
    else
    {
        QGraphicsItem::mousePressEvent(event);
    }
}

void ItemBase::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_isResizing)
    {
        m_isResizing = false;
    }
    else if (event->button() == Qt::LeftButton && m_isRotating)
    {
        m_isRotating = false;
    }
    else
    {
        QGraphicsItem::mouseReleaseEvent(event);
    }
}

void ItemBase::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_Delete:
        deleteSelectedItems(scene());
        break;
    case Qt::Key_Insert:
        duplicateSelectedItems(scene());
        break;
    case Qt::Key_Plus:
        growSelectedItems(scene());
        break;
    case Qt::Key_Minus:
        shrinkSelectedItems(scene());
        break;
    default:
        QGraphicsItem::keyPressEvent(event);
        break;
    }
}

void ItemBase::wheelEvent(QGraphicsSceneWheelEvent *event)
{
    prepareGeometryChange();
    m_size = ));
    if (m_size > MAX_ITEM_SIZE)
        m_size = MAX_ITEM_SIZE;
    else if (m_size < MIN_ITEM_SIZE)
        m_size = MIN_ITEM_SIZE;
}

int ItemBase::type() const
{
    return Type;
}

bool ItemBase::isInResizeArea(const QPointF &pos)
{
    );
}

bool ItemBase::isInRotateArea(const QPointF &pos)
{
     <= pos.x()
            && pos.x() <= 
            && -m_size /  <= pos.y()
            && pos.y() <= -m_size / )
    {
        return true;
    }
    else
    {
        return false;
    }
}

#ifndef MYITEM_H
#define MYITEM_H

#include "ItemBase.h"

class MyItem : public ItemBase
{
public:
    MyItem(int size, int x, int y);
    virtual ~MyItem() override;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;

protected:
    ItemBase *createNew(int size, int x, int y) override;
};

#endif // MYITEM_H

#include "MyItem.h"
#include <QPainter>

MyItem::MyItem(int size, int x, int y)
    : ItemBase (size, x, y)
{

}

MyItem::~MyItem()
{

}

void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->setRenderHint(QPainter::Antialiasing, true);
    QVector<QLine> vec;
    QLine l1(-m_size * );
    QLine l2(-m_size * );
    QLine l3(-m_size * );
    QLine l4(-m_size * );
    vec.push_back(l1);
    vec.push_back(l2);
    vec.push_back(l3);
    vec.push_back(l4);
    painter->drawLines(vec);

ItemBase::paint(painter, option, widget);
}

ItemBase *MyItem::createNew(int size, int x, int y)
{
    return new MyItem(size, x, y);
}

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class QGraphicsView;
class QGraphicsScene;
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    QGraphicsView   *m_view;
    QGraphicsScene  *m_scene;
};

#endif // MAINWINDOW_H

#include "MainWindow.h"
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QRandomGenerator>
#include "MyItem.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    m_scene = new QGraphicsScene(this);
    m_scene->setSceneRect();
    m_view = new QGraphicsView(this);
    m_view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    m_view->setScene(m_scene);
    setCentralWidget(m_view);

QSize size = m_scene->sceneRect().size().toSize();
    m_scene->addItem(,
                                QRandomGenerator::global()->bounded(size.height() - ));
}

MainWindow::~MainWindow()
{

}

测试运行:

QGraphicsItem鼠标旋转控制研究的更多相关文章

  1. QGraphicsItem鼠标精准拾取(pick/select)研究

    在QT场景视图中,一个2D图形项是一个QGraphicsItem,我们可以通过继承来定义我们自己的图形项. 主要有以下三个虚函数需要重点关注: 1)   边界矩形(必须实现) virtual QRec ...

  2. threejs和3d各种效果的学习

    写给即将开始threejs学习的自己,各种尝试,各种记忆.不要怕,灰色的年华终会过去. 一个技术学习的快慢,以及你的深刻程度,还有你的以后遇到这个东西的时候的反应速度,很大程度上,取决于你的博客的深刻 ...

  3. Unity模拟龙之谷人物行走简单控制

    我个人挺喜欢龙之谷(DN)的人物控制的(不是广告哈....),就是人物太萌了一点,动作.打击感都挺好的. 今天用Unity简单模仿了一下DN的人物控制,当然,游戏里面动作非常多,我这里仅仅做了简单的w ...

  4. QQuickPaintedItem鼠标精准拾取(pick/select)研究

    QT C++在2D图形方面已经做的很完善了,在PC端(Windows.Linux和MaC)上都有很好的表现. QT中的QML特别适合于移动端应用的开发,QML中的一些基本形状类型并不是一一地与Qt C ...

  5. 由chrome剪贴板问题研究到了js模拟鼠标键盘事件

    写在前面 最近公司在搞浏览器兼容的事情,所有浏览器兼容的问题不得不一个人包了.下面来说一下今天遇到的一个问题吧 大家都知道IE下面如果要获得剪贴板里面的信息的话,代码应该如下所示 window.cli ...

  6. 【移动端兼容问题研究】javascript事件机制详解(涉及移动兼容)

    前言 这篇博客有点长,如果你是高手请您读一读,能对其中的一些误点提出来,以免我误人子弟,并且帮助我提高 如果你是javascript菜鸟,建议您好好读一读,真的理解下来会有不一样的收获 在下才疏学浅, ...

  7. 手持设备点击响应速度,鼠标事件与touch事件的那些事

    前言 现在一直在做移动端的开发,这次将单页应用的网页内嵌入了app,于是老大反映了一个问题:app应用点击响应慢!我开始不以为然,于是拿着网页版的试了试,好像确实有一定延迟,于是开始了研究,最后选择了 ...

  8. 对html与body的一些研究与理解

    by zhangxinxu from http://www.zhangxinxu.com本文地址:http://www.zhangxinxu.com/wordpress/?p=259 一.写在前面的最 ...

  9. WebGIS中矢量切图的初步研究

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1.背景 在GIS领域,金字塔技术一直是一个基础性技术,WMTS规范专 ...

随机推荐

  1. 201871010105-曹玉中《面向对象程序设计(java)》第十五周学习总结

    201871010105-曹玉中<面向对象程序设计(java)>第十五周学习总结 项目 内容 这个作业属于哪个过程 https://www.cnblogs.com/nwnu-daizh/ ...

  2. Python运维中20个常用的库和模块

    1.psutil是一个跨平台库(https://github.com/giampaolo/psutil) 能够实现获取系统运行的进程和系统利用率(内存,CPU,磁盘,网络等),主要用于系统监控,分析和 ...

  3. 迪杰斯特拉算法完整代码(Java)

    package com.rao.graph; import java.util.*; /** * @author Srao * @className Dijkstra * @date 2019/12/ ...

  4. nexus php composer 私服搭建

    nexus 社区也提供了php composer 私服(当前还在开发中,还没有ga),测试使用构建好的docker 镜像 环境准备 docker-compose 文件 version: "3 ...

  5. itsdangerous模块

    使用场景: 在取消订阅时,可以在URL里序列化并且签名一个用户的ID或在任何的激活账户的链接或类似的情形下使用.这种情况下不需要生成一个一次性的token并把它们存到数据库中. 被签名的对象可以被存入 ...

  6. Asp.Net Core 中的环境变量

    Asp.Net Core 中的环境变量 软件开发环境在大多数软件开发组织中,我们通常具有以下开发环境. 开发环境--Development 演示(模拟.临时)环境--Staging 生产环境-- Pr ...

  7. 字符串s倒序输出

    编程将字符串s倒序输出,要求利用函数递归实现. 输入格式要求:"%s" 提示信息:"input your string:\n" 输出格式要求:"%c& ...

  8. [LeetCode] 14. Longest Common Prefix 最长共同前缀

    Write a function to find the longest common prefix string amongst an array of strings. If there is n ...

  9. python开发--信息处理系统

    #!/usr/bin/python card_list=[] #定义列表变量 def show_menu(): print("*" * 10) print("名片管理系统 ...

  10. [转载]3.14 UiPath图片操作截图的介绍和使用

    一.截图(Take Screenshot)的介绍 截取指定的UI元素屏幕截图的一种活动,输出量仅支持图像变量(image) 二.Take Screenshot在UiPath中的使用 1.打开设计器,在 ...