-
Notifications
You must be signed in to change notification settings - Fork 0
/
myitem.cpp
77 lines (65 loc) · 1.77 KB
/
myitem.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
#include "myitem.h"
#include <QPainter>
#include <QCursor>
#include <QGraphicsSceneMouseEvent>
#include <QApplication>
#include <QDrag>
#include <QMimeData>
#include <QPixmap>
#include <QWidget>
MyItem::MyItem()
{
setToolTip("Click and drag me");
setCursor(QCursor(Qt::OpenHandCursor));
setFlag(QGraphicsItem::ItemIsFocusable);
setFlag(QGraphicsItem::ItemIsMovable);
}
QRectF MyItem::boundingRect() const
{
qreal penWidth = 1;
return QRectF(0-penWidth/2, 0-penWidth/2, 20+penWidth, 20+penWidth);
}
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
auto isCollided = !collidingItems().isEmpty();
painter->setBrush(isCollided ? Qt::red : color);
painter->drawEllipse(0, 0, 20, 20);
}
void MyItem::mousePressEvent(QGraphicsSceneMouseEvent *e)
{
if (e->button() != Qt::LeftButton) {
e->ignore();
return;
}
setCursor(QCursor(Qt::ClosedHandCursor));
}
void MyItem::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{
bool isDrag = QLineF(e->screenPos(), e->buttonDownScreenPos(Qt::LeftButton)).length() >= QApplication::startDragDistance();
if (!isDrag) {
return;
}
auto drag = new QDrag(e->widget());
auto mime = new QMimeData;
drag->setMimeData(mime);
mime->setColorData(color);
QPixmap pix(21, 21);
pix.fill(Qt::transparent);
QPainter painter(&pix);
paint(&painter, nullptr, nullptr);
drag->setPixmap(pix);
drag->setHotSpot(QPoint(10, 15));
drag->exec();
setCursor(QCursor(Qt::OpenHandCursor));
}
void MyItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *e)
{
Q_UNUSED(e);
setCursor(QCursor(Qt::OpenHandCursor));
}
void MyItem::keyPressEvent(QKeyEvent *e)
{
moveBy(0, 10);
}