main.cpp
#include <QGuiApplication>
#include <mainwindow.h>
#include <QDebug>
#include <QString>
#include <QSize>
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
MainWindow* mainwindow = new MainWindow;
QQmlEngine *engine = mainwindow->engine();
engine->addImageProvider("qrcode", mainwindow);
mainwindow->setSource(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QQuickImageProvider>
#include <QQmlExtensionPlugin>
#include <QQuickView>
class MainWindow:public QQuickView ,public QQuickImageProvider
{
public:
MainWindow();
QPixmap generateQRcode(QString tempstr);
QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize);
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include <QPainter>
extern "C"
{
#include "./QRCode/config.h"
#include "./QRCode/mask.h"
#include "./QRCode/mmask.h"
#include "./QRCode/mqrspec.h"
#include "./QRCode/qrencode.h"
#include "./QRCode/qrencode_inner.h"
#include "./QRCode/qrinput.h"
#include "./QRCode/qrspec.h"
#include "./QRCode/rscode.h"
#include "./QRCode/split.h"
#include "./QRCode/bitstream.h"
}
MainWindow::MainWindow():QQuickImageProvider(QQuickImageProvider::Pixmap)
{
}
QPixmap MainWindow::generateQRcode(QString tempstr)
{
QRcode *qrcode; //二维码数据
//QR_ECLEVEL_Q 容错等级
char* ch;
QByteArray ba = tempstr.toUtf8();
ch=ba.data();
qrcode = QRcode_encodeString(ch, 2, QR_ECLEVEL_Q, QR_MODE_8, 1);
qint32 temp_width= 200; //二维码图片的大小
qint32 temp_height= 200;
qint32 qrcode_width = qrcode->width > 0 ? qrcode->width : 1;
double scale_x = (double)temp_width / (double)qrcode_width; //二维码图片的缩放比例
double scale_y =(double) temp_height /(double) qrcode_width;
QImage mainimg=QImage(temp_width,temp_height,QImage::Format_ARGB32);
QPainter painter(&mainimg);
QColor background(Qt::white);
painter.setBrush(background);
painter.setPen(Qt::NoPen);
painter.drawRect(0, 0, temp_width, temp_height);
QColor foreground(Qt::black);
painter.setBrush(foreground);
for( qint32 y = 0; y < qrcode_width; y ++)
{
for(qint32 x = 0; x < qrcode_width; x++)
{
unsigned char b = qrcode->data[y * qrcode_width + x];
if(b & 0x01)
{
QRectF r(x * scale_x, y * scale_y, scale_x, scale_y);
painter.drawRects(&r, 1);
}
}
}
QPixmap mainmap = QPixmap::fromImage(mainimg);
return mainmap;
}
QPixmap MainWindow::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
int width = 200;
int height = 200;
if (size)
*size = QSize(width, height);
QPixmap pixmap(requestedSize.width() > 0 ? requestedSize.width() : width,
requestedSize.height() > 0 ? requestedSize.height() : height);
pixmap = generateQRcode("我是一只小白兔");
return pixmap;
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Image {
id: qrcode
anchors.centerIn: parent
height: 200
width: 200
source: "image://qrcode/";
}
}