一、引言
本文针对之前的自定义验证码的标签控件(如下)进行完善
1、不区分大小写(小写输入验证)
2、实时更新验证码颜色
二、效果
三、源码
头文件:
#ifndef VERIFICATION_H
#define VERIFICATION_H
#include <QPaintEvent>
#include <QPainter>
#include <QTimer>
#include <QTime>
#include <QPushButton>
class Verification : public QPushButton
{
Q_OBJECT
public:
explicit Verification(QWidget *parent = nullptr);
Qt::GlobalColor* getColor();
void paintEvent(QPaintEvent *event);
QString m_captcha;
Qt::GlobalColor* m_color;
QTimer *m_timer;
enum {
NUMBER_FLAG,
UPLETTER_FLAG,
LOWLETTER_FLAG
};
signals:
public slots:
QString getCaptcha();
void TimeoutSlot();
};
#endif // VERIFICATION_H
源文件:
#include "verification.h"
const int letter_number = 4;//产生字符的数量
Verification::Verification(QWidget *parent) : QPushButton(parent)
{
m_timer = new QTimer(this);
qsrand(QTime::currentTime().second() * 1000 + QTime::currentTime().msec());
m_captcha = getCaptcha();
m_color = getColor();
connect(m_timer,SIGNAL(timeout()),this,SLOT(TimeoutSlot()));
m_timer->start(200);
connect(this,SIGNAL(clicked(bool)),this,SLOT(getCaptcha()));
}
/*****************************************************************
* 函数名称: getCaptcha
* 功能描述: 随机生成验证码(数字或英文字母)
* 参数说明: 无
* 返回值: 字符串类型的4位验证码
* 修改记录:
* 日期: 2022-02-25 修改人: zqw
* 描述:
* 日期: 2022-02-25 修改人: zqw
* 描述:
******************************************************************/
QString Verification::getCaptcha()
{
QString c = "";
QString ret = "";
for(int i = 0; i < 4; i++){
int flag = qrand() % letter_number;
switch (flag)
{
case NUMBER_FLAG:c='0' + qrand() % 10; break;
case UPLETTER_FLAG:c='A' + qrand() % 26; break;
case LOWLETTER_FLAG:c='a' + qrand() % 26; break;
default:c=qrand() % 2 ? 'W' : 'D';
}
ret += c;
}
this->setText(ret.toLower());
m_captcha = ret;
return m_captcha;
}
/*****************************************************************
* 函数名称: getColor
* 功能描述: 获取随机的颜色
* 参数说明: 无
* 返回值: Qt::GlobalColor
* 修改记录:
* 日期: 2022-02-25 修改人: zqw
* 描述:
* 日期: 2022-02-25 修改人: zqw
* 描述:
******************************************************************/
Qt::GlobalColor *Verification::getColor()
{
static Qt::GlobalColor colors[4];
for(int i = 0; i < 4; i++)
{
colors[i] = static_cast<Qt::GlobalColor>((qrand() % 16) + 2);
}
return colors;
}
/*****************************************************************
* 函数名称: paintEvent
* 功能描述: 绘制噪点和验证码
* 参数说明: 绘制事件
* 返回值: 无
* 修改记录:
* 日期: 2022-02-25 修改人: zqw
* 描述:
* 日期: 2022-02-25 修改人: zqw
* 描述:
******************************************************************/
void Verification::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(0, 0, 84, 24, Qt::white);
painter.setFont(QFont("Comic Sans MS"));
//绘制噪点
for(int i = 0; i < 100; i++){
painter.setPen(m_color[i % 4]);
painter.drawPoint(0 + (qrand() % 84), 0 + (qrand() % 24));
}
//绘制验证码
for(int i = 0; i < 4; i++){
painter.setPen(m_color[i]);
painter.drawText(0 + 20 * i, 0, 20, 24, Qt::AlignCenter, QString(m_captcha[i]));
}
}
void Verification::TimeoutSlot()
{
m_color = getColor();
update();
}
原创不易,转载请标明出处: