在本机C / C ++中使用Qt绘制QR代码 [英] Drawing QR code with Qt in native C/C++
本文介绍了在本机C / C ++中使用Qt绘制QR代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已成功在 QLabel
上绘制并显示了 QrCode
,但是在扫描时无法识别。这是我使用的代码-我用静态函数制作了一个小类:
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);
}
}
}
}
在这里称呼它:
QPixmap map(400,400);
QPainter painter(&map);
QrCodeDrawer::paintQR(painter,QSize(400,400),"Hello World", QColor("white"));
ui.qrCode->setPixmap(map);
我给 Hello World作为输入字符串,这是我得到的代码:
I gave "Hello World" as input string and here is the code I get:
I got the source code from here.
推荐答案
我使用了相同的示例,但是在使用垃圾QR代码时遇到了问题,直到我意识到 str
可能是一个悬空的指针。我将代码更改为此,并且效果很好:
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:
void QrCodeDrawer::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:
QrCode qr = QrCode::encodeText(data.toUtf8().constData(), QrCode::Ecc::HIGH);
这篇关于在本机C / C ++中使用Qt绘制QR代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文