天天看點

Qt滑塊圖檔驗證碼

Qt滑塊圖檔驗證碼

文章目錄

    • Qt滑塊圖檔驗證碼
      • (一)、控件介紹
        • (二)、效果圖
      • 核心代碼
        • 工程檔案
        • 結尾

(一)、控件介紹

  1. 自定義随機圖檔
  2. 滑動條滑動驗證
  3. 重定義驗證圖檔
  4. 摳圖位置随機

(二)、效果圖

Qt滑塊圖檔驗證碼
Qt滑塊圖檔驗證碼

核心代碼

void PuzzleWidget::setPixmap(const QString& pixmap)
{
	m_pixmap = pixmap;
	QTimer::singleShot(10, this, SLOT(onUpdatePixmap()));
}

void PuzzleWidget::onUpdatePixmap()
{
	m_offsetPoint.rx() = qBound(0, qrand() % this->width() + squarewidth + squareradius, this->width() - squarewidth - squareradius);
	m_offsetPoint.ry() = qBound(0, qrand() % this->height() + squarewidth + squareradius, this->height() - squarewidth - squareradius);
	update();
}

void PuzzleWidget::setValue(int value)
{
	m_value = qBound(0, value, this->width() - squarewidth - squareradius + m_offsetPoint.x());
	update();
}

void PuzzleWidget::paintEvent(QPaintEvent *event)
{
	QPainter painter(this);
	painter.setRenderHints(QPainter::Antialiasing);
	QPainterPath clippath;
	clippath.addRoundedRect(this->rect(), 4, 4);
	painter.setClipPath(clippath);
	const QPixmap& pixmap = QPixmap(m_pixmap).scaled(this->width(), this->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
	painter.drawPixmap(0, 0, this->width(), this->height(), pixmap);

	QPainterPath cutoutpath;
	cutoutpath.setFillRule(Qt::WindingFill);
	QRect rect(m_offsetPoint, QSize(squarewidth, squarewidth));
	cutoutpath.addRoundedRect(rect, 2, 2);
	cutoutpath.addEllipse(rect.center().x() - squareradius / 2, rect.top() - squareradius + 6, squareradius, squareradius);
	QPainterPath subellipseparh;
	subellipseparh.addEllipse(rect.right() - squareradius + 6, rect.center().y() - squareradius / 2, squareradius, squareradius);
	cutoutpath -= subellipseparh;

	painter.setPen(QPen(QColor(80, 80, 80), 1));
	painter.setBrush(QColor(100, 100, 100, 220));
	painter.drawPath(cutoutpath);

	QPixmap puzzlePixmap(this->size());
	puzzlePixmap.fill(Qt::transparent);
	QPainter puzzlePainter(&puzzlePixmap);
	puzzlePainter.setRenderHints(QPainter::Antialiasing);
	puzzlePainter.setClipPath(cutoutpath);
	puzzlePainter.setPen(QPen(QColor(80, 80, 80), 2));
	puzzlePainter.setBrush(QColor(200, 200, 200, 100));
	puzzlePainter.drawPixmap(0, 0, this->width(), this->height(), pixmap);
	puzzlePainter.drawPath(cutoutpath);

	painter.drawPixmap(-m_offsetPoint.x() + m_value, 0, this->width(), this->height(), puzzlePixmap);
}

bool PuzzleWidget::isOverlap()
{
	return qAbs(-m_offsetPoint.x() + m_value) < 5;
}
           

工程檔案

Qt交流大會(收費群) 853086607

QQ 3246214072

Qt滑塊圖檔驗證碼

結尾

不定期上傳新作品,解答群中作品相關問題。相關外,能解答則解答。歡迎大家一起探索Qt世界

繼續閱讀