Qt :圆圈加载进度条(转圈圈)

本文介绍如何使用Qt绘制圆形和环形的加载动画。通过QPainterPath和QConicalGradient实现渐变色圆弧的绘制,利用定时器实现动画效果。
该文章已生成可运行项目,

两种样式

圆形
在这里插入图片描述
环形
在这里插入图片描述

源码

头文件
这里没有使用任何ui文件

继承QDialog,设置标题栏隐藏,并设置为模态(阻塞父窗口):目的是为了让用户不能进行任何操作

#pragma once
#include <QDialog>
class JcProcessBar :
	public QDialog
{
	Q_OBJECT
public:
	JcProcessBar(QWidget* pParent = nullptr);
	~JcProcessBar();
	void paintEvent(QPaintEvent *event);
private slots:
	void  updaterRotation();
private:
	double rotation = 0.0;
	QTimer *timer = nullptr;
};

cpp

#include "stdafx.h"
#include "JcProcessBar.h"
#include<QPainter>
#include<QTimer>
#include <QDebug>
JcProcessBar::JcProcessBar(QWidget* pParent  ): QDialog(pParent)
{
	this->resize(100, 100);
	timer = new QTimer();
	connect(timer, &QTimer::timeout, this, &JcProcessBar::updaterRotation);// 定时旋转坐标系
	timer->start(10); 
	this->setModal(true);//设置为模态,该窗口不关闭,父窗口不能操作
	//隐藏标题栏
	//this->setWindowFlags(Qt::FramelessWindowHint);
	this->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
	//背景透明
	setAttribute(Qt::WA_TranslucentBackground, true);
}


JcProcessBar::~JcProcessBar()
{
	if (timer)
	{
		delete timer;
		timer = nullptr;
	}
}
void  JcProcessBar::updaterRotation()
{
	rotation++;
	if (rotation == 360)
	{
		rotation = 0;
	}
	update();
}
void JcProcessBar::paintEvent(QPaintEvent *event)
{//根据QPaintPath画出渐变色的圆弧
	int width = this->width();
	int height = this->height();
	int side = qMin(width, height);

	QPainter painter(this);
	painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
	painter.translate(width / 2, height / 2);
	painter.scale(side / 200.0, side / 200.0);

	QConicalGradient gra(QPoint(0, 0), 0);
	gra.setColorAt(0, QColor("#3BB6FE"));
	gra.setColorAt(1, QColor("#FFFFFF"));
	QBrush brush(gra);

	int radis = 40;
	int sider = 10;
	QRect rect(-radis, -radis, radis * 2, radis * 2);
	QPainterPath path;
	path.arcTo(rect, 0, 270);
 
	QPainterPath subPath;
	subPath.addEllipse(rect.adjusted(sider, sider, -sider, -sider));
	//这行注释掉就是圆形,加上去就是环形
	//path = path - subPath;
	painter.setBrush(brush);
	painter.setPen(Qt::NoPen);
	painter.rotate(rotation);
	painter.drawPath(path);
}

 

这里使用QPainterPath 绘图
首先绘制 270°的圆使用

	QRect rect(-radis, -radis, radis * 2, radis * 2);
	QPainterPath path;
	path.arcTo(rect, 0, 270);

也就是第一张图

如果要绘制圆环,就再定义一个 QPainterPath

	QPainterPath subPath;
	subPath.addEllipse(rect.adjusted(sider, sider, -sider, -sider));

相减得到圆环

path = path - subPath;
本文章已经生成可运行项目
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值