qrcodewidget.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "qrcodewidget.h"
  2. QRCodeWidget::QRCodeWidget(QWidget* parent)
  3. : QWidget(parent)
  4. {
  5. m_qrcodeVersion = 2;
  6. }
  7. QRCodeWidget::~QRCodeWidget()
  8. {
  9. }
  10. void QRCodeWidget::paintEvent(QPaintEvent* event)
  11. {
  12. QPainter painter;
  13. painter.begin(this);
  14. int qrcodeWidth = width() < height() ? width() : height();
  15. qrcodeWidth = qrcodeWidth - 4;
  16. int blockWidth = qrcodeWidth / m_qrcodeWidth;
  17. int qrcodeTop = (height() - qrcodeWidth) / 2;
  18. int qrcodeLeft = (width() - qrcodeWidth) / 2;
  19. for (int i = 0; i < m_blocks.count(); i++) {
  20. QRCodeBlock block = m_blocks.at(i);
  21. QRect rc = QRect(block.x * blockWidth + qrcodeLeft, block.y * blockWidth + qrcodeTop, blockWidth, blockWidth);
  22. if (block.data == 1) {
  23. painter.fillRect(rc, Qt::black);
  24. } else {
  25. painter.fillRect(rc, Qt::white);
  26. }
  27. }
  28. painter.end();
  29. }
  30. void QRCodeWidget::resizeEvent(QResizeEvent* event)
  31. {
  32. update();
  33. }
  34. int QRCodeWidget::qrcodeVersion() const
  35. {
  36. return m_qrcodeVersion;
  37. }
  38. void QRCodeWidget::setQrcodeVersion(int qrcodeVersion)
  39. {
  40. m_qrcodeVersion = qrcodeVersion;
  41. }
  42. QString QRCodeWidget::qrcode() const
  43. {
  44. return m_qrcode;
  45. }
  46. void QRCodeWidget::setQrcode(const QString& qrcode)
  47. {
  48. m_qrcode = qrcode;
  49. QRcode* code;
  50. code = QRcode_encodeString(qrcode.toLocal8Bit().data(), m_qrcodeVersion, QR_ECLEVEL_L, QR_MODE_8, 0);
  51. m_blocks.clear();
  52. m_qrcodeWidth = code->width;
  53. for (int i = 0; i < code->width; i++) {
  54. QString s = "";
  55. for (int j = 0; j < code->width; j++) {
  56. QRCodeBlock block;
  57. block.x = j;
  58. block.y = i;
  59. if (code->data[i * 25 + j] & 0x01) {
  60. block.data = 1;
  61. } else {
  62. block.data = 0;
  63. }
  64. m_blocks << block;
  65. }
  66. }
  67. delete code;
  68. update();
  69. }