qml绘制二维码

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);
            }
        }
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值