需求:我们想生成一个二维码,看到网上有很多,但是总是感觉很乱,就自己写下来记录,想要更加的详细一点
环境: vs 2019 + qt5.12
1.第三方库Libqrencode
Libqrencode:一个第三方的生成二维码的库
下载网址:https://fukuchi.org/works/qrencode/
下载下来:
1.我们需要将源码中config.h.in 改为 config.h
2.将解压下来的 不是.h 和 .c 的文件都删除 ,留下如下面的
3.我们可以用两种方式
第一种:我们生成一个.pro文件在pro文件中添加宏定义:DEFINES += HAVE_CONFIG_H;
第二种:vs-》c/c++ 的预处理器 中直接添加 HAVE_CONFIG_H;
4.在config.h文件中重新定义 MAJOR_VERSION、MICRO_VERSION、MINOR_VERSION、VERSION,重新定义的方法:找到#undef MAJOR_VERSION位置,在其下面定义#define MAJOR_VERSION 1,就是紫色部分如下:
5.建立个QT程序,将我们删除 后的文件夹 复制到我们的工程下,改名为qrencode(也可以不改):
6.右键我们的工程—》添加-》添加现有项-》添加到我们的工程中
注:qrenc.c文件不要加 进来 ,如果加进来编译会报错
7.将我们的包含目录加进来
8.源码
#pragma once
#include <QtWidgets/QWidget>
#include "ui_QRecode_Test2.h"
#include "qrencode.h"
#include <QPainter>
#include <QLabel>
class QRecode_Test2 : public QWidget
{
Q_OBJECT
public:
QRecode_Test2(QWidget *parent = Q_NULLPTR);
public slots:
void on_pushButton_clicked();
private:
Ui::QRecode_Test2Class ui;
};
#include "QRcode_Test.h"
#include <QDebug>
QRcode_Test::QRcode_Test(QWidget* parent)
: QWidget(parent)
{
ui.setupUi(this);
}
void QRcode_Test::on_pushButton_clicked()
{
QString strUrl = ui.textEdit_url->toPlainText();
if (strUrl.isEmpty())
return;
QRcode* qrcode;
qrcode = QRcode_encodeString(strUrl.toStdString().c_str(), 2, QR_ECLEVEL_Q, QR_MODE_8, 1);
qint32 temp_width = 500;
qint32 temp_height = 500;
qDebug() << "temp_width=" << temp_width << ";temp_height=" << temp_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;
int offset = 14;
QImage mainimg = QImage(temp_width + offset * 2, temp_height + offset * 2, QImage::Format_ARGB32);
QPainter painter(&mainimg);
QColor background(Qt::white);
painter.setBrush(background);
painter.setPen(Qt::NoPen);
painter.drawRect(offset, offset, 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(offset + x * scale_x, offset + y * scale_y, scale_x, scale_y);
painter.drawRects(&r, 1);
}
}
}
painter.setPen(QColor(0, 0, 255));
painter.drawText(temp_width / 2, temp_height + offset * 2 - 2, strUrl);
QPixmap mainmap = QPixmap::fromImage(mainimg);
QLabel* m_pQrlabel = new QLabel();
m_pQrlabel->setWindowFlags(Qt::WindowCloseButtonHint);
m_pQrlabel->setAttribute(Qt::WA_QuitOnClose, false);
m_pQrlabel->setPixmap(mainmap);
m_pQrlabel->setVisible(true);
m_pQrlabel->setToolTip(strUrl);
m_pQrlabel->setWindowTitle(QStringLiteral("本地生成二维码:") + strUrl);
mainmap.save(QCoreApplication::applicationDirPath() + "\\qrcode_local.jpg", Q_NULLPTR, 100);
}
运行结果: