Класс виджета небольшого приложения рисующего граффические примитивы

 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
#include "drawwindget.h"
#include <QPainter>
#include <QMouseEvent>
#include <QRect>
#include <QDrag>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
void DrawWidget::drawCenterLineForRect(QPainter& painter){
for(int i = 1; i < this->__rectList.size(); i++){
painter.drawLine(this->__rectList[i - 1].x() + 10, this->__rectList[i - 1].y() + 10, this->__rectList[i].x() + 10, this->__rectList[i].y() + 10);
}
}
DrawWidget::DrawWidget(){
__fl = false;
__moveAll = false;
__moveRect = NULL;
__moveIndex = -1;
}
void DrawWidget::mousePressEvent(QMouseEvent *event){
int x = event->x();
int y = event->y();
switch(event->button()){
case Qt::LeftButton:{
this->__moveAll = false;
__fl = true;
__moveIndex = -1;
for(int i = 0; i < __rectList.size(); i++){
if(__rectList[i].contains(x, y)){
return;
}
}
QRect rect;
rect.adjust(x - 10, y - 10, x + 10, y + 10);
this->__rectList.append(rect);
}
break;
case Qt::RightButton:{
__moveIndex = -1;
this->__moveAll = false;
for(int i = 0; i < __rectList.size(); i++){
if(__rectList[i].contains(x, y)){
__moveIndex = i;
return;
}
}
}
break;
case Qt::MidButton:{
__moveIndex = -1;
this->__moveAll = true;
for(int i = 0; i < __rectList.size(); i++){
if(__rectList[i].contains(x, y)){
__moveIndex = i;
return;
}
}
}
break;
}
update();
}
void DrawWidget::paintEvent(QPaintEvent *event){
if(__fl){
QPainter painter(this);
painter.setPen(Qt::blue);
painter.setFont(QFont("Arial", 30));
for(int i = 0; i < __rectList.size(); i++){
painter.drawRect(this->__rectList[i]);
}
for(int i = 0; i < __pointList.size(); i++){
painter.drawPoint(__pointList[i]);
}
this->drawCenterLineForRect(painter);
}
}
void DrawWidget::mouseMoveEvent(QMouseEvent *event){
if((event->buttons() & Qt::RightButton) && this->__moveIndex != -1){
//this->__moveRect->moveTo(event->x() - 10, event->y() - 10);
__rectList[__moveIndex].moveTo(event->x() - 10, event->y() - 10);
update();
}
if((event->buttons() & Qt::MidButton) && __moveAll){
int baseX = __rectList[__moveIndex].x();
int baseY = __rectList[__moveIndex].y();
for(int i = 0; i < __rectList.size(); i++){
int x = __rectList[i].x();
int y = __rectList[i].y();
__rectList[i].moveTo(x + (event->x() - baseX - 10), y + (event->y() - baseY - 10));
}
update();
}
}