-
Notifications
You must be signed in to change notification settings - Fork 0
/
qrwidget.cpp
127 lines (116 loc) · 2.65 KB
/
qrwidget.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
#include "qrwidget.h"
#include <QPainter>
#include <QImage>
QRWidget::QRWidget(QWidget *parent) : QWidget(parent)
{
qr = NULL;
setQRData("Hello QR Code");
}
QRWidget::~QRWidget()
{
if(qr != NULL)
{
QRcode_free(qr);
}
}
int QRWidget::getQRWidth() const
{
if(qr != NULL)
{
return qr->width;
}
else
{
return 0;
}
}
void QRWidget::setQRData(QString data)
{
QRData = data;
if(qr != NULL)
{
QRcode_free(qr);
}
qr = QRcode_encodeString(QRData.toStdString().c_str(),
1,
QR_ECLEVEL_L,
QR_MODE_8,
1);
update();
}
QSize QRWidget::sizeHint() const
{
QSize s;
if(qr != NULL)
{
int qr_width = qr->width > 0 ? qr->width : 1;
s = QSize(qr_width * 4, qr_width * 4);
}
else
{
s = QSize(50, 50);
}
return s;
}
QSize QRWidget::minimumSizeHint() const
{
QSize s;
if(qr != NULL)
{
int qr_width = qr->width > 0 ? qr->width : 1;
s = QSize(qr_width, qr_width);
}
else
{
s = QSize(50, 50);
}
return s;
}
bool QRWidget::saveImage(const QString &fileName, int size, int quality, const char* format)
{
if(size != 0 && !fileName.isEmpty())
{
QImage image(size, size, QImage::Format_Mono);
QPainter painter(&image);
draw(painter, size, size);
return image.save(fileName, format, quality);
}
else
{
return false;
}
}
void QRWidget::draw(QPainter &painter, int width, int height)
{
if(NULL != qr)
{
QColor background(Qt::white);
painter.setBrush(background);
painter.setPen(Qt::NoPen);
painter.drawRect(0, 0, width, height);
QColor foreground(Qt::black);
painter.setBrush(foreground);
const int qr_width = qr->width > 0 ? qr->width : 1;
const double scale=(double)((width > height) ? height : width)/qr_width*0.9;
const int x_first = (width - scale*qr_width)/2;
const int y_first = (height - scale*qr_width)/2;
unsigned char *data = qr->data;
for( int y = 0; y < qr_width; y ++)
{
for(int x = 0; x < qr_width; x++)
{
unsigned char b = *data++;
if(b & 0x01)
{
QRectF rect(x * scale + x_first, y * scale + y_first, scale, scale);
painter.drawRect(rect);
}
}
}
}
}
void QRWidget::paintEvent(QPaintEvent *)
{
QPainter painter(this);
draw(painter, width(), height());
}