Qt 二维码

1.生成二维码

 利用第三方库qrencode ,将qrencode源码添加到自己的程序中,直接调用使用.

 参考http://blog.csdn.net/zhangxufei/article/details/52149892

 1.qrencode-3.4.4文件夹复制到源代码下面,把*.h*.c文件加入到工程中。

2.在QT pro文件添加

DEFINES += HAVE_CONFIG_H

INCLUDEPATH += qrencode-3.4.4/

3.重新定义 MAJOR_VERSION、MICRO_VERSION、MINOR_VERSION、VERSION,重新定义的方法:找到#undef MAJOR_VERSION位置,在其下面定义#define MAJOR_VERSION 1,其他几个也这么定义;

需要到文件如下:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "qrencode.h"

#include <QPainter>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_GenerateQRCode_clicked()
{

     QString strCodeData=ui->lineEdit_CodeData->text();

     QByteArray ba = strCodeData.toLocal8Bit();
     char *codeData = ba.data();
     generateQRcode(codeData);

}


void MainWindow::generateQRcode(const char* codeData)
{

    //QR_ECLEVEL_Q 容错等级
    QRcode * qrcode = QRcode_encodeString(codeData, 2, QR_ECLEVEL_Q, QR_MODE_8, 1);

    qint32 tempWidth=ui->label->width(); //二维码图片的大小
    qint32 tempHeight=ui->label->height();
    qint32 qrcodeWidth = qrcode->width > 0 ? qrcode->width : 1;
    double scaleX = (double)tempWidth / (double)qrcodeWidth; //二维码图片的缩放比例
    double scaleY = (double) tempHeight /(double) qrcodeWidth;

   qDebug()<<"scale_x"<<scaleX;


    QImage mainImg=QImage(tempWidth,tempHeight,QImage::Format_ARGB32);
    QPainter painter(&mainImg);
    QColor background(Qt::white);
    painter.setBrush(background);
    painter.setPen(Qt::NoPen);
    painter.drawRect(0, 0, tempWidth, tempHeight);

    QColor foreground(Qt::black);
    painter.setBrush(foreground);
    for( qint32 y = 0; y < qrcodeWidth; y ++)
    {
        for(qint32 x = 0; x < qrcodeWidth; x++)
        {
            unsigned char b = qrcode->data[y * qrcodeWidth + x];
            if(b & 0x01)
            {
              QRectF r(x * scaleX, y * scaleY, scaleX, scaleY);
              painter.drawRects(&r, 1);
            }
        }
    }
    QPixmap codeImage=QPixmap::fromImage(mainImg);
    ui->label->setPixmap(codeImage);
    ui->label->setVisible(true);

}
原文地址:https://www.cnblogs.com/ike_li/p/6073939.html