2016 年 3 月 3 日更新: 我注意到有一个小型库项目可以完成我的回答,但以更“预先打包”的方式。您可以查看here。
Qt 中的二维码
有一个纯 C 语言的小型 QR 码生成器库,没有依赖项,称为 libqrencode。
第 1 步:安装
在您可以使用它之前,您必须先安装它。在我的 Ubuntu 13.10 上,这意味着在 shell 中输入以下内容:
sudo aptitude install libqrencode-dev
在其他平台上,您可能必须自己从源代码构建它。只需下载压缩包并按照source code download 的说明进行操作即可。
第 2 步:项目文件
接下来,您必须将库添加到您的项目中。在我的 Qt5.2.0 项目文件(myproject.pro 或类似文件)中,这意味着附加以下行:
LIBS += -lqrencode
这对于我知道的大多数 Qt 版本来说应该是相似的。
第 3 步:编码
接下来必须编写实际使用该库的代码,将某些输入字符串编码为 QR 格式。那是一行代码:
QRcode *qr=QRcode_encodeString("my string", 1, QR_ECLEVEL_L, QR_MODE_8,0);
注意:在试验了我传递给这个函数的参数后,我了解到需要小心。一些参数组合无缘无故地失败了。例如传递 0 作为版本或使用 QR_MODE_AN 失败并出现“无效参数”。这可能是我正在使用的旧版本库中的错误您已被警告。
第 4 步:渲染图像
最后,在清理之前,您需要将输出转换为位图,以便可以在屏幕上渲染。这比听起来简单。我不会列出一堆假设,而是在这里包含我完整的工作简约 QRWidget 实现。有趣的部分在被覆盖的 paintEvent() 方法中。
QRWidget.hpp
#ifndef QRWIDGET_HPP
#define QRWIDGET_HPP
#include <QWidget>
class QRWidget : public QWidget{
Q_OBJECT
private:
QString data;
public:
explicit QRWidget(QWidget *parent = 0);
void setQRData(QString data);
protected:
void paintEvent(QPaintEvent *);
};
#endif // QRWIDGET_HPP
QRWidget.cpp
#include "QRWidget.hpp"
#include <QPainter>
#include <QDebug>
#include <qrencode.h>
QRWidget::QRWidget(QWidget *parent) :
QWidget(parent),
data("Hello QR")//Note: The encoding fails with empty string so I just default to something else. Use the setQRData() call to change this.
{
}
void QRWidget::setQRData(QString data){
this->data=data;
update();
}
void QRWidget::paintEvent(QPaintEvent *pe){
QPainter painter(this);
//NOTE: I have hardcoded some parameters here that would make more sense as variables.
QRcode *qr = QRcode_encodeString(data.toStdString().c_str(), 1, QR_ECLEVEL_L, QR_MODE_8, 0);
if(0!=qr){
QColor fg("black");
QColor bg("white");
painter.setBrush(bg);
painter.setPen(Qt::NoPen);
painter.drawRect(0,0,width(),height());
painter.setBrush(fg);
const int s=qr->width>0?qr->width:1;
const double w=width();
const double h=height();
const double aspect=w/h;
const double scale=((aspect>1.0)?h:w)/s;
for(int y=0;y<s;y++){
const int yy=y*s;
for(int x=0;x<s;x++){
const int xx=yy+x;
const unsigned char b=qr->data[xx];
if(b &0x01){
const double rx1=x*scale, ry1=y*scale;
QRectF r(rx1, ry1, scale, scale);
painter.drawRects(&r,1);
}
}
}
QRcode_free(qr);
}
else{
QColor error("red");
painter.setBrush(error);
painter.drawRect(0,0,width(),height());
qDebug()<<"QR FAIL: "<< strerror(errno);
}
qr=0;
}
总结
在这篇小文章中,我总结了使用 Qt 使用 QR 码生成器的经验。