安装依赖库
sudo apt-get install libqrencode-dev libpng12-dev
在Qt的pro文件中添加动态库链接
LIBS += -lqrencode
上代码
头文件qrcodelabel.h
#ifndef QRCODELABEL_H
#define QRCODELABEL_H
#include <QLabel>
#include <QPainter>
#include <qrencode.h>
#include <QPaintEvent>
class QRcodeLabel : public QLabel
{
Q_OBJECT
public:
explicit QRcodeLabel(QWidget *parent = Q_NULLPTR);
~QRcodeLabel();
void setString(const QString str);
void setLogo(const QString path);
protected:
virtual void paintEvent(QPaintEvent *ev);
private:
QRcode* qrcode;
QPixmap* image;
bool logo;
};
#endif // QRCODELABEL_H
源文件qrcodelabel.cpp
#include "qrcodelabel.h"
QRcodeLabel::QRcodeLabel(QWidget *parent) :
QLabel(parent)
{
qrcode = NULL;
}
QRcodeLabel::~QRcodeLabel()
{
if(qrcode != NULL) {
QRcode_free(qrcode);
}
}
void QRcodeLabel::setString(const QString str)
{
if(qrcode != NULL) {
QRcode_free(qrcode);
}
qrcode = QRcode_encodeString(str.toStdString().c_str(), 2, QR_ECLEVEL_H, QR_MODE_8, 1);
update();
}
void QRcodeLabel::setLogo(const QString path)
{
image = new QPixmap(path);
logo = true;
update();
}
void QRcodeLabel::paintEvent(QPaintEvent *ev)
{
Q_UNUSED(ev);
if(qrcode)
return;
int width = this->width();
int height = this->height();
int qrWidth = qrcode->width > 0 ? qrcode->width : 1 ;
double scaleX = (double)width / (double)qrWidth ;
double scaleY = (double)height / (double)qrWidth ;
QPainter painter(this);
painter.setBrush(Qt::white);
painter.setPen(Qt::NoPen);
painter.drawRect(this->rect());
painter.setBrush(Qt::black);
for(int y = 0; y < qrWidth; ++y) {
for(int x = 0; x < qrWidth; ++x) {
uchar node = qrcode->data[y*qrWidth + x];
if(node & 0x01) {
QRectF rectf(x*scaleX, y*scaleY, scaleX, scaleY);
painter.drawRects(&rectf, 1);
}
}
}
if(logo) {
int logoW = width * 0.2;
int logoH = height * 0.2;
QRect rect((width-logoW)/2, (height-logoH)/2, logoW, logoH);
painter.setPen(QPen(Qt::red, 3));
painter.drawRect(rect);
painter.drawPixmap(rect, image->copy());
logo = false;
}
}
main.cpp
#include "qrcodelabel.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QRcodeLabel w;
w.resize(200, 200);
w.setString("12345678");
w.show();
return a.exec();
}
参考链接