Qt实现验证码功能控件

效果图:

在这里插入图片描述
原理
随机挑选数字或者字母,随机选取颜色,通过绘制实现数字和字母验证码以及背景噪点

核心代码

//随机获取验证码数字和字母
QString Verification::getVerificationCodeByRand()
{
	QString destCode = QString();
	for (int i = 0; i < m_codeNum; i++) {
		int flag = qrand() % 2;
		if (0 == flag) {
			int c = '0' + qrand() % 10;
			destCode += static_cast<QChar>(c);
		}
		else {
			int c = (qrand() % 2) ? 'a' : 'A';
			destCode += static_cast<QChar>(c + qrand() % 26);
		}
	}
	return destCode;
}

//随机获取颜色
Qt::GlobalColor * Verification::getColors()
{
	static Qt::GlobalColor colors[4];
	for (int i = 0; i < 4; i++)
	{
		colors[i] = static_cast<Qt::GlobalColor>(2 + qrand() % 16);
	}
	return colors;
}

//绘制
void Verification::paintEvent(QPaintEvent * event)
{
	QPainter painter(this);
	//填充验证码绘制矩形
	painter.fillRect(0, 0, 100, 30, QColor(255, 250, 240));
	painter.setFont(QFont("Comic Sans MS", 12));

	//绘制验证码
	for (int i = 0; i < m_codeNum; i++)
	{
		painter.setPen(m_colors[i]);
		painter.drawText(25 * i, 0, 25, 30, Qt::AlignCenter, QString(m_verificationCode[i]));
	}

	//绘制噪点
	if (m_bstyle == BackgroundStyle::E_DOT)
		paintDot(&painter);
}

//绘制噪点
void Verification::paintDot(QPainter * painter)
{
	if (Q_NULLPTR == painter)
		return;

	//绘制噪点
	for (int i = 0; i < 150; i++)
	{
		painter->setPen(m_colors[i % 4]);
		painter->drawPoint(qrand() % 99, qrand() % 29);
	}
}

源码传送门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

离歌漠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值