1、下载QR Code 源码
2、二维码绘图头文件
#ifndef QRCODEGENERATOR_H
#define QRCODEGENERATOR_H
#include <QQuickPaintedItem>
#include <QImage>
#include "qrencode.h"
class QRCodeGenerator : public QQuickPaintedItem
{
Q_OBJECT
public:
explicit QRCodeGenerator(QQuickItem *parent = nullptr);
// 绘制二维码
Q_INVOKABLE void paintQRCode(QString str, int width, int height);
// 绘图
virtual void paint(QPainter *painter);
signals:
private:
QRcode *qr;
QImage img;
qreal width;
qreal height;
};
#endif // QRCODEGENERATOR_H
3、二维码绘图cpp
#include "qrcodegenerator.h"
#include <QDebug>
#include <QPainter>
QRCodeGenerator::QRCodeGenerator(QQuickItem *parent) : QQuickPaintedItem(parent)
{
qr = nullptr;
}
void QRCodeGenerator::paintQRCode(QString str, int width, int height)
{
if (qr != nullptr)
{
QRcode_free(qr);
}
qr = QRcode_encodeString(str.toStdString().c_str(), 1, QR_ECLEVEL_L, QR_MODE_8, 1);
if (qr == nullptr)
{
qDebug()<<__FILE__<<__FUNCTION__<<__LINE__<<"generate QRCode failed!";
return;
}
this->width = width;
this->height = height;
update();
}
void QRCodeGenerator::paint(QPainter *painter)
{
QColor foreground(Qt::black);
painter->setBrush(foreground);
const int qr_width = qr->width > 0 ? qr->width : 1;
double scale_x = width / qr_width;
double scale_y = height / qr_width;
for( int y = 0; y < qr_width; y ++)
{
for(int x = 0; x < qr_width; x++)
{
unsigned char b = qr->data[y * qr_width + x];
if(b & 0x01)
{
QRectF r(int(x * scale_x), int(y * scale_y), int(scale_x), int(scale_y));
painter->drawRects(&r, 1);
}
}
}
}