使用QT在ARM板子下实现显示二维码

版权声明:本文为 风筝 博主原创文章,转载请署名出处!!谢谢合作。文章地址: https://blog.csdn.net/Guet_Kite/article/details/89848552

你好!这里是风筝的博客,

欢迎和我一起交流。


最近在做毕设,需要在ARM板子上实现显示一个二维码,所以参考了网上一些文章,给予后来人方便。
这里需要到一个libqrencode。可以去官网下载:https://fukuchi.org/works/qrencode/
当然,也可以在CSDN的资源里找找,花点积分就能下载到,我用的是qrencode-3.4.4
下载解压即可。
在QT下建立工程:
 1.将qrencode源码中的(*.h *.c)加入到工程中(在工程项目右键点击Add Existing Directory…)(但是不要添加qrenc.c文件,因为会报错!);
 2.将qrencode源码中的config.h.in文件修改成config.h并加入工程;
 3.在QT的pro文件中添加DEFINES += HAVE_CONFIG_H 定义全局宏定义;
 4.重新定义 MAJOR_VERSION、MICRO_VERSION、MINOR_VERSION、VERSION;重新定义的方法:找到#undef MAJOR_VERSION位置(在config.h里),在其下面定义#define MAJOR_VERSION 1,其他几个也这么定义;

这样修改后,就可以在程序中使用qrencode来生成二维码。
代码如下,其中ui->label_5是我自己添加的一个lable。

void Widget::slotGenerateQRcode(QString tempstr,int width, int height)
{
    //qDebug() << "slotGenerateQRcode";
    QRcode *qrcode; //二维码数据
    //QR_ECLEVEL_Q 容错等级
    qrcode = QRcode_encodeString(tempstr.toStdString().c_str(), 2, QR_ECLEVEL_Q, QR_MODE_8, 1);
    //qrcode = QRcode_encodeString("http://www.baidu.com/", 2, QR_ECLEVEL_Q, QR_MODE_8, 0);
    ui->label_5->setGeometry(QRect(75,0,width,height));//二维码位置
    ui->label_5->resize(width,height);//设置二维码大小
    qint32 temp_width=ui->label_5->width(); //二维码图片的大小
    qint32 temp_height=ui->label_5->height();
    qint32 qrcode_width = qrcode->width > 0 ? qrcode->width : 1;
    double scale_x = (double)temp_width / (double)qrcode_width; //二维码图片的缩放比例
    double scale_y =(double) temp_height /(double) qrcode_width;
    QImage mainimg=QImage(temp_width,temp_height,QImage::Format_ARGB32);
    QPainter painter(&mainimg);
    QColor background(Qt::white);
    painter.setBrush(background);
    painter.setPen(Qt::NoPen);
    painter.drawRect(0, 0, temp_width, temp_height);
    QColor foreground(Qt::black);
    painter.setBrush(foreground);
    for( qint32 y = 0; y < qrcode_width; y ++)
    {
        for(qint32 x = 0; x < qrcode_width; x++)
        {
            unsigned char b = qrcode->data[y * qrcode_width + x];
            if(b & 0x01)
            {
                QRectF r(x * scale_x, y * scale_y, scale_x, scale_y);
                painter.drawRects(&r, 1);
            }
        }
    }
    QPixmap mainmap=QPixmap::fromImage(mainimg);
    ui->label_5->setPixmap(mainmap);
    ui->label_5->setVisible(true);
}

调用这个即可显示二维码。

最后,感谢这篇文章:QT中实现二维码图片生成

参考:
window下基于libqrencode库,采用QT开发环境实现一个简单的QR二维码生成

猜你喜欢

转载自blog.csdn.net/Guet_Kite/article/details/89848552