Qt 打印二维码

配置文件加入打印机支持:

QT += printsupport

新建名称为MyQRCode的Widget项目,在项目目录下建立qrlib文件夹

通过以下地址下载三方支持库:

https://github.com/nayuki/QR-Code-generator

把cpp目录下以下六个文件拷贝到qrlib文件夹下

通过添加现有文件,把qr库文件加入项目:

效果如下:

通过添加新文件加入新的头文件及class文件:

在生成的头文件(myqrcode.h)里下加入下代码:

myqrcode.h

#ifndef MYQRCODE_H
#define MYQRCODE_H

#include <QObject>

#include <QPrinter>
#include <QPainter>
#include "qrlib/QrCode.hpp"

class MyQRCode : public QObject
{
    Q_OBJECT
public:
    explicit MyQRCode(QObject *parent = nullptr);
    void paintQR(QPainter &painter, QPoint point,const QSize sz, const QString &data, QColor fg);

signals:

public slots:
};

#endif // MYQRCODE_H

myqrcode.cpp

#include "myqrcode.h"

MyQRCode::MyQRCode(QObject *parent) : QObject(parent)
{

}

void MyQRCode::paintQR(QPainter &painter, QPoint point, const QSize sz, const QString &data, QColor fg)
{
    qrcodegen::QrCode qr = qrcodegen::QrCode::encodeText(data.toUtf8().constData(), qrcodegen::QrCode::Ecc::LOW);
    const int s=qr.getSize()>0?qr.getSize():1;
    const double w=sz.width();
    const double h=sz.height();
    const double aspect=w/h;
    const double size=((aspect>1.0)?h:w);
    const double scale=size/(s+2);
    // NOTE: For performance reasons my implementation only draws the foreground parts in supplied color.
    // It expects background to be prepared already (in white or whatever is preferred).
    painter.setPen(Qt::NoPen);
    painter.setBrush(fg);
    for(int y=0; y<s; y++) {
        for(int x=0; x<s; x++) {
            const int color=qr.getModule(x, y);  // 0 for white, 1 for black
            if(0!=color) {
                const double rx1=(x+1)*scale+point.x(), ry1=(y+1)*scale+point.y();
                QRectF r(rx1, ry1, scale, scale);
                painter.drawRects(&r,1);
            }
        }
    }
}

在mainwindow.h引入头文件(myqrcode.h)和增加printQRCode函数接口:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include "myqrcode.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    printQRCode();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

在mainwindow.cpp里增加printQRCode函数实现:

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    printQRCode();
}

MainWindow::~MainWindow()
{
    delete ui;
}

MainWindow::printQRCode()
{
    QPrinter printer;
//    printer.setPrinterName("DASCOM DS-650Pro"); //打印机名称
    printer.setPrinterName("CutePDF Writer");
    QPainter painter(&printer);

    QSize size;
    size.setWidth(300);
    size.setHeight(300);
    MyQRCode qr;
    qr.paintQR(painter,QPoint(150,200),size,"你好 渣渣曦",QColor(0, 160, 230));
    painter.end();
}

PDF打印机打印结果如下:

猜你喜欢

转载自my.oschina.net/zhizhisoft/blog/1802662