QT實現簡單驗證碼
阿新 • • 發佈:2018-06-01
ase 窗口 事件 實現 draw date() res pragma init
主要思路:
在QT designer 中繪制QLabel控件
自定義類繼承QLabel類,並提升至控件
提升至
生成隨機數
重寫paintEvent繪制圖形
重寫mousePressEvent刷新驗證碼
註意當窗口大小、焦點發生變化時均可觸發paintEvent函數。
繪制控件
在窗口中添加QLabel控件並布局
自定義驗證碼類
.h文件
1 #pragma once 2 #include <QLabel> 3 #include <QPaintEvent> 4 #include <QPainter> 5 #include <QTime> 6class VerificationCodeLabel : public QLabel 7 { 8 public: 9 VerificationCodeLabel(QWidget *parent = 0); 10 ~VerificationCodeLabel(); 11 protected: 12 //重寫繪制事件,以此來生成驗證碼 13 void paintEvent(QPaintEvent *event); 14 void mousePressEvent(QMouseEvent *ev); 15 private: 16 const int letter_number = 4;//產生字符的數量 17 int noice_point_number;//噪點的數量 18 //生成驗證碼 19 void produceVerificationCode(); 20 //產生隨機的字符 21 QChar produceRandomLetter(); 22 //產生隨機的顏色 23 void produceRandomColor(); 24 25 QChar *verificationCode; 26 QColor *colorArray; 27 };
.cpp文件
1 VerificationCodeLabel::VerificationCodeLabel(QWidget *parent): QLabel(parent)2 { 3 //生成隨機種子 4 qsrand(QTime::currentTime().second() * 1000 + QTime::currentTime().msec()); 5 colorArray = new QColor[letter_number]; 6 verificationCode = new QChar[letter_number]; 7 noice_point_number = this->width()*4; 8 } 9 10 VerificationCodeLabel::~VerificationCodeLabel() 11 { 12 13 } 14 //重寫繪制事件,以此來生成驗證碼 15 void VerificationCodeLabel::paintEvent(QPaintEvent *event) 16 { 17 QPainter painter(this); 18 QPoint p; 19 //產生4個不同的字符 20 produceVerificationCode(); 21 //產生4個不同的顏色 22 produceRandomColor(); 23 //繪制驗證碼 24 for (int i = 0; i < letter_number; ++i) 25 { 26 p.setX(i*(this->width() / letter_number) + this->width() / 16); 27 p.setY(this->height()/1.5); 28 painter.setPen(colorArray[i]); 29 painter.drawText(p, QString(verificationCode[i])); 30 } 31 //繪制噪點 32 for (int j = 0; j < noice_point_number; ++j) 33 { 34 p.setX(qrand() % this->width()); 35 p.setY(qrand() % this->height()); 36 painter.setPen(colorArray[j % 4]); 37 painter.drawPoint(p); 38 } 39 return; 40 } 41 //這是一個用來生成驗證碼的函數 42 void VerificationCodeLabel::produceVerificationCode() 43 { 44 for (int i = 0; i < letter_number; ++i) 45 verificationCode[i] = produceRandomLetter(); 46 return; 47 } 48 //產生一個隨機的字符 49 QChar VerificationCodeLabel::produceRandomLetter() 50 { 51 QChar c; 52 int flag = qrand() % letter_number; 53 switch (flag) 54 { 55 case 0: 56 c = ‘0‘ + qrand() % 10; 57 break; 58 case 1: 59 c = ‘A‘ + qrand() % 26; 60 break; 61 case 2: 62 c = ‘a‘ + qrand() % 26; 63 break; 64 default: 65 c = ‘0‘ + qrand() % 10; 66 break; 67 } 68 return c; 69 } 70 //產生隨機的顏色 71 void VerificationCodeLabel::produceRandomColor() 72 { 73 for (int i = 0; i < letter_number; ++i) 74 colorArray[i] = QColor(qrand() % 255, qrand() % 255, qrand() % 255); 75 return; 76 } 77 78 void VerificationCodeLabel::mousePressEvent(QMouseEvent *ev) 79 { 80 update(); 81 }
自定義類提升至控件
運行結果
參考:
https://blog.csdn.net/wjh_init/article/details/79163275
QT實現簡單驗證碼