主要思路:
在QT designer 中绘制QLabel控件
自定义类继承QLabel类,并提升至控件
提升至
生成随机数
重写paintEvent绘制图形
重写mousePressEvent刷新验证码
注意当窗口大小、焦点发生变化时均可触发paintEvent函数。
绘制控件
在窗口中添加QLabel控件并布局
自定义验证码类
.h文件
1 #pragma once 2 #include <QLabel> 3 #include <QPaintEvent> 4 #include <QPainter> 5 #include <QTime> 6 class 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 }
自定义类提升至控件
运行结果
参考: