Mika avatar

How to draw QR codes using Qt library

mtl1979

Published: 06 Jun 2020 › Updated: 06 Jun 2020How to draw QR codes using Qt library

How to draw QR codes using Qt library

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 

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 

#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.

Leave How to draw QR codes using Qt library to:

Written by

Freelance journalist, software designer

Read more #programming posts


Best Posts From Mika

We have not curated any of mtl1979's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Mika