-
Notifications
You must be signed in to change notification settings - Fork 2
/
QImgViewWidget.cpp
93 lines (84 loc) · 2.35 KB
/
QImgViewWidget.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
#include "QImgViewWidget.h"
#include <QPainter>
#include <QWheelEvent>
QImgViewWidget::QImgViewWidget(QWidget * parent):QWidget(parent)
{
zoom_scale_ = 1.0f;
move_start_ = false;
is_moving_ = false;
}
void QImgViewWidget::SetImage(const QImage& img)
{
// reset the transformation
ResetTransform();
QSize view_size = size();
// loading by QImage
img_display_ = img;
pix_ori_ = QPixmap::fromImage(img_display_);
if(pix_ori_.isNull()) return;
pix_display_ = pix_ori_.scaled(zoom_scale_ * size(), Qt::KeepAspectRatio);
}
void QImgViewWidget::ResetTransform()
{
// reset the zoom scale and move step
zoom_scale_ = 1.0f;
move_step_ = QPoint(0, 0);
}
void QImgViewWidget::paintEvent(QPaintEvent* event)
{
// rander the loading image
// TODO(Ethan): It's slow and memory confusing when zooming in
if(pix_display_.isNull()) return;
QPainter painter(this);
painter.drawPixmap(move_step_.x() +(width() - pix_display_.width()) / 2, move_step_ .y()+ (height() - pix_display_.height()) / 2, pix_display_);
}
void QImgViewWidget::wheelEvent(QWheelEvent* event)
{
// zoom in and out when scrolling mouse
if (event->delta() > 0) {
zoom_scale_ *= 1.1;
}
else {
zoom_scale_ *= 0.9;
}
// TODO(Ethan): It's slow and memory confusing when zooming in
if(!pix_ori_.isNull())
pix_display_ = pix_ori_.scaled(zoom_scale_ * size(), Qt::KeepAspectRatio);
update();
}
void QImgViewWidget::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton) {
if (!move_start_) {
move_start_ = true;
is_moving_ = false;
mouse_point_ = event->globalPos();
}
}
}
void QImgViewWidget::mouseReleaseEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton) {
if(move_start_) {
move_start_ = false;
is_moving_ = false;
}
}
}
void QImgViewWidget::mouseMoveEvent(QMouseEvent* event)
{
// move image when moving mouse
if (move_start_) {
const QPoint mos_pt = event->globalPos();
move_step_ += mos_pt - mouse_point_;
is_moving_ = true;
mouse_point_ = mos_pt;
repaint();
}
}
void QImgViewWidget::resizeEvent(QResizeEvent* event)
{
if(!pix_ori_.isNull())
pix_display_ = pix_ori_.scaled(zoom_scale_ * size(), Qt::KeepAspectRatio);
update();
}