关于验证码
- 验证码必须随机生成。
- 验证码必须有一定的识别难度。
关于解决方案
- 随机产生目标验证码。
- 验证码中的字符颜色随机变化。
- 在验证码区域随机绘制噪点。
- 利用已有组件进行重新实现。
头文件
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;
signals:
public slots:
QString getCaptcha();
void TimeoutSlot();
};
源文件
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()));
}
QString Verification::getCaptcha()
{
QString ret = "";
for(int i = 0; i < 4; i++){
int c = (qrand() % 2) ? 'a' : 'A';
ret += static_cast(c + qrand() % 26);
}
m_captcha = ret;
return ret;
}
Qt::GlobalColor *Verification::getColor()
{
static Qt::GlobalColor colors[4];
for(int i = 0; i < 4; i++)
{
colors[i] = static_cast((qrand() % 16) + 2);
}
return colors;
}
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();
}



