Quantcast
Viewing all articles
Browse latest Browse all 4

Answer by Nayuki for How to draw a QR code with Qt in native C/C++

If you feel that Fukuchi's library is too large[0] for you, consider looking at Nayuki's C++ QR Code generator library[1]: https://github.com/nayuki/QR-Code-generator/tree/master/cpp

Nayuki's library requires C++11, and is portable without needing Autotools. Sample usage:

#include <string>#include <vector>#include "QrCode.hpp"using namespace qrcodegen;// Create the QR Code objectQrCode qr = QrCode::encodeText("Hello, world!", QrCode::Ecc::MEDIUM);// Read the black & white pixelsfor (int y = 0; y < qr.size; y++) {    for (int x = 0; x < qr.size; x++) {        int color = qr.getModule(x, y);  // 0 for white, 1 for black        // You need to modify this part        draw_pixel_onto_QT(x, y, color);    }}

[0]: Fukuchi: 20 files, ~7200 lines among the main .c and .h files (excluding build and test code).
[1]: Nayuki: 6 files, ~1400 lines among the main .cpp and .hpp files (excluding demo code).


EDIT 2016-12-08 by OPI decided, with permission, to add my own adaption to Qt. This code compiles and runs fine on my system, And I think it should be independent enough to work elsewhere without too many tweaks as well.

#include "QrCode.hpp"void paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg){    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:    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, ry1=(y+1)*scale;                QRectF r(rx1, ry1, scale, scale);                painter.drawRects(&r,1);            }        }    }}

For usage, please see this painter class.


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>