Qt实现验证码功能控件

效果图:

Qt实现验证码功能控件_第1张图片
原理
随机挑选数字或者字母,随机选取颜色,通过绘制实现数字和字母验证码以及背景噪点

核心代码

//随机获取验证码数字和字母
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);
	}
}

源码传送门

你可能感兴趣的:(Qt,c++,qt5)