Qt生成二維碼需要第三方庫qrencode。
1、編譯好的qrencode庫獲取:
鏈接:https://pan.baidu.com/s/1rss-9LlDVmJ-mfNmK_dELQ
提取碼:h8lc
2、Qt配置qrencode
(1)右擊Qt工程文件,出現菜單,選擇【添加庫】->【外部庫】來添加qrencode庫。
(2)把qrencode.h頭文件添加到工程中,然后包含頭文件 #include "qrencode.h"
3、代碼生成二維碼
1 /** 2 * @brief GernerateQRCode 3 * 生成二維碼函數 4 * @param text 二維碼內容 5 * @param qrPixmap 二維碼像素圖 6 * @param scale 二維碼縮放比例 7 */ 8 void GernerateQRCode(const QString &text, QPixmap &qrPixmap, int scale) 9 { 10 if(text.isEmpty()) 11 { 12 return; 13 } 14 15 //二維碼數據 16 QRcode *qrCode = nullptr; 17 18 //這里二維碼版本傳入參數是2,實際上二維碼生成后,它的版本是根據二維碼內容來決定的 19 qrCode = QRcode_encodeString(text.toStdString().c_str(), 2, 20 QR_ECLEVEL_Q, QR_MODE_8, 1); 21 22 if(nullptr == qrCode) 23 { 24 return; 25 } 26 27 int qrCode_Width = qrCode->width > 0 ? qrCode->width : 1; 28 int width = scale * qrCode_Width; 29 int height = scale * qrCode_Width; 30 31 QImage image(width, height, QImage::Format_ARGB32_Premultiplied); 32 33 QPainter painter(&image); 34 QColor background(Qt::white); 35 painter.setBrush(background); 36 painter.setPen(Qt::NoPen); 37 painter.drawRect(0, 0, width, height); 38 QColor foreground(Qt::black); 39 painter.setBrush(foreground); 40 for(int y = 0; y < qrCode_Width; ++y) 41 { 42 for(int x = 0; x < qrCode_Width; ++x) 43 { 44 unsigned char character = qrCode->data[y * qrCode_Width + x]; 45 if(character & 0x01) 46 { 47 QRect rect(x * scale, y * scale, scale, scale); 48 painter.drawRects(&rect, 1); 49 } 50 } 51 } 52 53 qrPixmap = QPixmap::fromImage(image); 54 QRcode_free(qrCode); 55 }
1 void slot_GenerateQRCode() 2 { 3 QPixmap qrPixmap; 4 int width = ui->label_ShowQRCode->width(); 5 int height = ui->label_ShowQRCode->height(); 6 GernerateQRCode(ui->textEdit_Text->toPlainText(), qrPixmap, 2); 7 qrPixmap = qrPixmap.scaled(QSize(width, height), 8 Qt::IgnoreAspectRatio, Qt::SmoothTransformation); 9 ui->label_ShowQRCode->setPixmap(qrPixmap); 10 }
4、結果