Qt生成二维码需要第三方库qrencode。
1、编译好的qrencode库获取:
链接:https://pan.baidu.com/s/1rss-9LlDVmJ-mfNmK_dELQ
提取码:h8lc
2、Qt配置qrencode
(1)右击Qt工程文件,出现菜单,选择【添加库】->【外部库】来添加qrencode库。
(2)把qrencode.h头文件添加到工程中,然后包含头文件 #include "qrencode.h"
3、代码生成二维码

1 /**
2 * @brief GernerateQRCode
3 * 生成二维码函数
4 * @param text 二维码内容
5 * @param qrPixmap 二维码像素图
6 * @param scale 二维码缩放比例
7 */
8 void GernerateQRCode(const QString &text, QPixmap &qrPixmap, int scale)
9 {
10 if(text.isEmpty())
11 {
12 return;
13 }
14
15 //二维码数据
16 QRcode *qrCode = nullptr;
17
18 //这里二维码版本传入参数是2,实际上二维码生成后,它的版本是根据二维码内容来决定的
19 qrCode = QRcode_encodeString(text.toStdString().c_str(), 2,
20 QR_ECLEVEL_Q, QR_MODE_8, 1);
21
22 if(nullptr == qrCode)
23 {
24 return;
25 }
26
27 int qrCode_Width = qrCode->width > 0 ? qrCode->width : 1;
28 int width = scale * qrCode_Width;
29 int height = scale * qrCode_Width;
30
31 QImage image(width, height, QImage::Format_ARGB32_Premultiplied);
32
33 QPainter painter(&image);
34 QColor background(Qt::white);
35 painter.setBrush(background);
36 painter.setPen(Qt::NoPen);
37 painter.drawRect(0, 0, width, height);
38 QColor foreground(Qt::black);
39 painter.setBrush(foreground);
40 for(int y = 0; y < qrCode_Width; ++y)
41 {
42 for(int x = 0; x < qrCode_Width; ++x)
43 {
44 unsigned char character = qrCode->data[y * qrCode_Width + x];
45 if(character & 0x01)
46 {
47 QRect rect(x * scale, y * scale, scale, scale);
48 painter.drawRects(&rect, 1);
49 }
50 }
51 }
52
53 qrPixmap = QPixmap::fromImage(image);
54 QRcode_free(qrCode);
55 }


1 void slot_GenerateQRCode()
2 {
3 QPixmap qrPixmap;
4 int width = ui->label_ShowQRCode->width();
5 int height = ui->label_ShowQRCode->height();
6 GernerateQRCode(ui->textEdit_Text->toPlainText(), qrPixmap, 2);
7 qrPixmap = qrPixmap.scaled(QSize(width, height),
8 Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
9 ui->label_ShowQRCode->setPixmap(qrPixmap);
10 }

4、结果

这篇博客介绍了如何在Qt环境中利用qrencode库生成二维码。首先提供了qrencode库的下载链接和提取码,然后详细阐述了在Qt工程中配置qrencode库的步骤。接着展示了一个生成二维码的C++函数`GernerateQRCode`,该函数接受二维码内容、像素图和缩放比例作为参数,并通过调用qrencode库生成并绘制二维码。最后,给出了一个槽函数`slot_GenerateQRCode`,用于实际生成和显示二维码的示例。





