Add profile to printer support:
QT += printsupport
Create a new Widget project named MyQRCode, and create the qrlib folder in the project directory
Download the tripartite support library from:
https://github.com/nayuki/QR-Code-generator
Copy the following six files in the cpp directory to the qrlib folder
Add the qr library file to the project by adding an existing file:
The effect is as follows:
Add a new header file and class file by adding a new file:
Add the following code to the generated header file (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); } } } }
Introduce the header file (myqrcode.h) in mainwindow.h and add the printQRCode function interface:
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
Add the printQRCode function in mainwindow.cpp to realize:
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 name printer.setPrinterName("CutePDF Writer"); QPainter painter(&printer); QSize size; size.setWidth(300); size.setHeight(300); MyQRCode qr; qr.paintQR(painter,QPoint(150,200),size,"Hello, dregs",QColor(0, 160, 230)); painter.end(); }
The printing results of PDF printer are as follows: