示例
先放一下效果图
每次验证码输入错误或者点击验证码图片都可以进行验证码的刷新
正文
- 用到的是
QFrame
需要用到UI
里的类提升,自建一个新的设计师类,系统会自动生成.h和.cpp
我这里的类名用的是Ver
,有需要的自行替换即可
Ver.h
#ifndef VER_H
#define VER_H#include <QFrame>
#include <QLabel>
#include <QString>namespace Ui {
class Ver;
}class Ver : public QFrame
{Q_OBJECTpublic:explicit Ver(QWidget *parent = nullptr);~Ver();void generateRandomNumber(); //生成随机的数字和字母void paintEvent(QPaintEvent *); //画噪点和线void mousePressEvent(QMouseEvent *event); //鼠标点击事件QString code;private:};#endif // VER_H
Ver.cpp
#include "ver.h"#include <QPainter>
#include <QStyleOption>
#include <QLineEdit>
#include <QTime>
#include <QChar>
#include <QDebug>Ver::Ver(QWidget *parent) :QFrame(parent)
{//paintEvent();generateRandomNumber();update();
}Ver::~Ver()
{}void Ver::generateRandomNumber()
{code.clear();for(int i = 0;i < 4;++i){int num = qrand()%3;if(num == 0){//数字code += QString::number(qrand()%10);}else if(num == 1){//大写字母int temp = 'A';code += static_cast<QChar>(temp + qrand()%26);}else if(num == 2){//小写字母int temp = 'a';code += static_cast<QChar>(temp + qrand()%26);}}
}void Ver::paintEvent(QPaintEvent *) //绘画
{QPainter painter(this);QPen pen;//画点for(int i = 0;i < 100;++i) {pen = QPen(QColor(qrand()%256,qrand()%256,qrand()%256));painter.setPen(pen);painter.drawPoint(qrand()%150,qrand()%50);}//画线for(int i = 0;i < 10;++i) {painter.drawLine(qrand()%150,qrand()%50,qrand()%150,qrand()%50);}pen = QPen(QColor(255,0,0,100));QFont font("楷体",25,QFont::Bold,true);painter.setFont(font);painter.setPen(pen);//绘画字for(int i = 0;i < 4;++i) {painter.drawText(10+30*i,5,30,40,Qt::AlignCenter, QString(code[i]));}//ui->ver->setText(code);
}void Ver::mousePressEvent(QMouseEvent *event)
{generateRandomNumber();update();// qDebug() << code << endl;
}