2024-02-27 12:23:24 +08:00
|
|
|
#include "FluQrCodeItem.h"
|
2023-08-08 15:44:10 +08:00
|
|
|
|
2023-12-13 17:31:08 +08:00
|
|
|
#include "qrcode/qrencode.h"
|
2023-08-08 15:44:10 +08:00
|
|
|
|
2024-04-11 14:51:43 +08:00
|
|
|
FluQrCodeItem::FluQrCodeItem(QQuickItem *parent) : QQuickPaintedItem(parent) {
|
|
|
|
_color = QColor(0, 0, 0, 255);
|
|
|
|
_bgColor = QColor(255, 255, 255, 255);
|
|
|
|
_size = 100;
|
2023-08-08 15:44:10 +08:00
|
|
|
setWidth(_size);
|
|
|
|
setHeight(_size);
|
2024-04-11 14:51:43 +08:00
|
|
|
connect(this, &FluQrCodeItem::textChanged, this, [=] { update(); });
|
|
|
|
connect(this, &FluQrCodeItem::colorChanged, this, [=] { update(); });
|
|
|
|
connect(this, &FluQrCodeItem::bgColorChanged, this, [=] { update(); });
|
|
|
|
connect(this, &FluQrCodeItem::sizeChanged, this, [=] {
|
2023-08-08 15:44:10 +08:00
|
|
|
setWidth(_size);
|
|
|
|
setHeight(_size);
|
|
|
|
update();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-04-11 14:51:43 +08:00
|
|
|
void FluQrCodeItem::paint(QPainter *painter) {
|
|
|
|
if (_text.isEmpty()) {
|
2023-08-08 15:44:10 +08:00
|
|
|
return;
|
|
|
|
}
|
2024-04-11 14:51:43 +08:00
|
|
|
if (_text.length() > 1024) {
|
2023-08-08 15:44:10 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
painter->save();
|
2023-12-13 17:31:08 +08:00
|
|
|
QRcode *qrcode = QRcode_encodeString(_text.toUtf8().constData(), 2, QR_ECLEVEL_Q, QR_MODE_8, 1);
|
2024-04-11 14:51:43 +08:00
|
|
|
auto w = qint32(width());
|
|
|
|
auto h = qint32(height());
|
2023-12-13 17:31:08 +08:00
|
|
|
qint32 qrcodeW = qrcode->width > 0 ? qrcode->width : 1;
|
2024-04-11 14:51:43 +08:00
|
|
|
double scaleX = (double) w / (double) qrcodeW;
|
|
|
|
double scaleY = (double) h / (double) qrcodeW;
|
2023-12-13 17:31:08 +08:00
|
|
|
QImage image = QImage(w, h, QImage::Format_ARGB32);
|
|
|
|
QPainter p(&image);
|
|
|
|
p.setBrush(_bgColor);
|
|
|
|
p.setPen(Qt::NoPen);
|
|
|
|
p.drawRect(0, 0, w, h);
|
|
|
|
p.setBrush(_color);
|
2024-04-11 14:51:43 +08:00
|
|
|
for (qint32 y = 0; y < qrcodeW; y++) {
|
|
|
|
for (qint32 x = 0; x < qrcodeW; x++) {
|
|
|
|
unsigned char b = qrcode->data[y * qrcodeW + x];
|
|
|
|
if (b & 0x01) {
|
|
|
|
QRectF r(x * scaleX, y * scaleY, scaleX, scaleY);
|
2023-12-13 17:31:08 +08:00
|
|
|
p.drawRects(&r, 1);
|
2023-08-14 18:10:37 +08:00
|
|
|
}
|
2023-08-08 15:44:10 +08:00
|
|
|
}
|
|
|
|
}
|
2023-12-13 17:31:08 +08:00
|
|
|
QPixmap pixmap = QPixmap::fromImage(image);
|
|
|
|
painter->drawPixmap(QRect(0, 0, static_cast<int>(width()), static_cast<int>(height())), pixmap);
|
2023-08-08 15:44:10 +08:00
|
|
|
painter->restore();
|
|
|
|
}
|