I am successfully drawing and displaying the QrCode
on a QLabel
, but it's not recognised when I scan it. Here is the code I used - I made a small class with a static function:
void QrCodeDrawer::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg)
{
char *str=data.toUtf8().data();
// NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
QrCode qr = QrCode::encodeText(str, QrCode::Ecc::HIGH);
const int s=qr.size>0?qr.size: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(0x0!=color) {
const double rx1=(x+1)*scale, ry1=(y+1)*scale;
QRectF r(rx1, ry1, scale, scale);
painter.drawRects(&r,1);
}
}
}
}
And called it here:
QPixmap map(400,400);
QPainter painter(&map);
QrCodeDrawer::paintQR(painter,QSize(400,400),"Hello World", QColor("white"));
ui.qrCode->setPixmap(map);
I gave "Hello World" as input string and here is the code I get:
I got the source code from here.
I finally solved it, by drawing the background first(white or any) and then draw the qr code on top of it with a different enough color...
I used the same sample but had problems with garbage QR codes until I realised
str
can be a dangling pointer. I changed my code to this and it worked fine: