How to draw QR codes using Qt librarysteemCreated with Sketch.

in #programming4 years ago

This simple class allows showing QR codes within applications using Qt 5.x series and supports Qt Designer. It requires libqrencode which is available for both Windows and Linux.

To set the contents for QR code, call showQRCode(). This simple version only supports encoding printable text.

QRLabel.h

// Copyright (c) 2011-2015 The Cryptonote developers
// Copyright (c) 2015 XDN developers
// Copyright (c) 2020 The Talleo developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#pragma once

#include <QLabel>

class QRLabel : public QLabel {
  Q_OBJECT
public:
  QRLabel(QWidget* _parent);
  ~QRLabel();

  void showQRCode(const QString& _dataString);
};

QRLabel.cpp

// Copyright (c) 2011-2015 The Cryptonote developers
// Copyright (c) 2015 XDN developers
// Copyright (c) 2020 The Talleo developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <QImage>

#include "libqrencode/qrencode.h"

#include "QRLabel.h"

QRLabel::QRLabel(QWidget* _parent) : QLabel(_parent) {}

QRLabel::~QRLabel() {}

void QRLabel::showQRCode(const QString& _dataString) {
  QRcode *qrcode = QRcode_encodeString(_dataString.toUtf8().constData(), 1, QR_ECLEVEL_L, QR_MODE_8, true);
  if (qrcode == nullptr) {
    return;
  }

  QImage qrCodeImage = QImage(qrcode->width + 8, qrcode->width + 8, QImage::Format_RGB32);
  qrCodeImage.fill(Qt::white);
  unsigned char *p = qrcode->data;
  for (int y = 0; y < qrcode->width; y++) {
    for (int x = 0; x < qrcode->width; x++) {
      if (*p & 1) {
        qrCodeImage.setPixelColor(x + 4, y + 4, Qt::black);
      }
      p++;
    }
  }

  QRcode_free(qrcode);
  setPixmap(QPixmap::fromImage(qrCodeImage));
  setEnabled(true);
}

Original code from DigitalNote (XDN), modifications and fixes by Talleo Project.

Coin Marketplace

STEEM 0.25
TRX 0.11
JST 0.032
BTC 63517.53
ETH 3062.83
USDT 1.00
SBD 3.81