1.简介
官网:https://fukuchi.org/works/qrencode/
Libqrencode 是一个快速紧凑的库,用于在 QR 码符号中编码数据,这是一个 2D 符号系统,可由方便的终端(如带 CCD 的手机)进行扫描。QR 码容量高达 7000 位或 4000 个字符,具有很高的鲁棒性。
Libqrencode 接受一个字符串或数据块列表,然后在 QR Code 符号中编码为位图数组。当其他 QR 码应用程序生成图像文件时,使用 libqrencode 允许应用程序直接从原始位图数据中呈现 QR 码符号。此库还包含命令行实用程序输出各种格式的 QR 码图像。
2.使用
去官网下载源码包,我这里使用最新的稳定版本qrencode-4.1.0,解压qrencode-4.1.0.tar.gz,新建一个Qt Widgets Application工程qrcodeDemo,然后执行以下步骤:
(1)将源码中的config.h.in文件修改成config.h;
(2)将qrencode源码中的(*.h *.c)加入到工程中(右键添加现有文件);
(3)在工程的pro文件中添加宏定义DEFINES += HAVE_CONFIG_H;
(4)在config.h中重新定义 MAJOR_VERSION、MICRO_VERSION、MINOR_VERSION、VERSION,重新定义的方法:找到#undef MAJOR_VERSION位置,在其下面定义#define MAJOR_VERSION 1,其他几个也这么定义;如下图所示:
修改完成后,就可以用qrencode库来生成二维码了,在mainwindow.cpp中引入qrencode.h头文件,在构造函数中调用二维码生成函数即可;如下图:
3.解决无法打开包括文件: “getopt.h”: No such file or directory的问题
编译时,会遇到getopt.h找不到的问题,是因为qrenc.c文件中引用了该头文件写了一个测试的main函数,并且只有该文件中用到了getopt.h头文件,所以直接屏蔽相关调用的地方即可,如下图所示:
(1)屏蔽头文件
(2)屏蔽结构体:
(3)屏蔽main函数
屏蔽完成后即可编译成功。
4.生成二维码图片
使用QT的QPainter来完成二维码图片的绘制,在mainwindow.ui中添加一个QLabel,使用如下函数即可生成二维码图片:
void MainWindow::GenerateQRcode(QString tempstr)
{
QRcode *qrcode; //二维码数据
//QR_ECLEVEL_Q 容错等级
qrcode = QRcode_encodeString(tempstr.toStdString().c_str(), 2, QR_ECLEVEL_Q, QR_MODE_8, 1);
qint32 temp_width=ui->label->width(); //二维码图片的大小
qint32 temp_height=ui->label->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->setPixmap(mainmap);
ui->label->setVisible(true);
}
5.最终效果:
6.源码
GitHub:https://github.com/liupeng2015bj/open-source-library.git,欢迎star。。。
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.youkuaiyun.com/struct_slllp_main/article/details/113753978