Qt:自定义一个好看的等待提示Ui控件

一、2024 永不卡顿

在这里插入图片描述

爱的魔力它转圈圈~
等待样式控件是我们在做UI时出场率还挺高的控件之一,通常情况下有如下的几种实现方式:
1> 获取一张gif的资源图,然后使用QMovie 在一个QLabel 控件上加载显示gif的waiting等待动态。
2> 自定义绘图,然后使用Qt动画,达到转圈圈的效果。本文以此方式为例,给大家一个好看的样式示例。

本篇,作为搬运工:https://github.com/snowwlex/QtWaitingSpinner

二、代码示例

使用草鸡简单,提供了一些接口,用于waiting 标签的修改。

#include <QCoreApplication>
#include <QApplication>
#include <waitingspinnerwidget.h>
#include <QFrame>
#include <QHBoxLayout>int main(int argc,char* argv[])
{QApplication a(argc,argv);WaitingSpinnerWidget* spinner = new WaitingSpinnerWidget;/// 设置waiting组件的样式spinner->setRoundness(70.0);spinner->setMinimumTrailOpacity(15.0);spinner->setTrailFadePercentage(70.0);spinner->setNumberOfLines(12);spinner->setLineLength(10);spinner->setLineWidth(5);spinner->setInnerRadius(10);spinner->setRevolutionsPerSecond(1);spinner->setColor(QColor(81, 4, 71));spinner->start(); // gets the show on the road!QFrame* f = new QFrame;QHBoxLayout* hlayout = new QHBoxLayout;hlayout->addWidget(spinner);f->setLayout(hlayout);f->show();return a.exec();
}

具体实现代码如下:

// waitingspinnerwidget.h/* Original Work Copyright (c) 2012-2014 Alexander TurkinModified 2014 by William HallattModified 2015 by Jacob Dawid
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/#pragma once// Qt includes
#include <QWidget>
#include <QTimer>
#include <QColor>class WaitingSpinnerWidget : public QWidget {Q_OBJECT
public:/*! Constructor for "standard" widget behaviour - use this* constructor if you wish to, e.g. embed your widget in another. */WaitingSpinnerWidget(QWidget *parent = 0,bool centerOnParent = true,bool disableParentWhenSpinning = true);/*! Constructor - use this constructor to automatically create a modal* ("blocking") spinner on top of the calling widget/window.  If a valid* parent widget is provided, "centreOnParent" will ensure that* QtWaitingSpinner automatically centres itself on it, if not,* "centreOnParent" is ignored. */WaitingSpinnerWidget(Qt::WindowModality modality,QWidget *parent = 0,bool centerOnParent = true,bool disableParentWhenSpinning = true);public slots:void start();void stop();public:void setColor(QColor color);void setRoundness(qreal roundness);void setMinimumTrailOpacity(qreal minimumTrailOpacity);void setTrailFadePercentage(qreal trail);void setRevolutionsPerSecond(qreal revolutionsPerSecond);void setNumberOfLines(int lines);void setLineLength(int length);void setLineWidth(int width);void setInnerRadius(int radius);void setText(QString text);QColor color();qreal roundness();qreal minimumTrailOpacity();qreal trailFadePercentage();qreal revolutionsPersSecond();int numberOfLines();int lineLength();int lineWidth();int innerRadius();bool isSpinning() const;private slots:void rotate();protected:void paintEvent(QPaintEvent *paintEvent);private:static int lineCountDistanceFromPrimary(int current, int primary,int totalNrOfLines);static QColor currentLineColor(int distance, int totalNrOfLines,qreal trailFadePerc, qreal minOpacity,QColor color);void initialize();void updateSize();void updateTimer();void updatePosition();private:QColor  _color;qreal   _roundness; // 0..100qreal   _minimumTrailOpacity;qreal   _trailFadePercentage;qreal   _revolutionsPerSecond;int     _numberOfLines;int     _lineLength;int     _lineWidth;int     _innerRadius;private:WaitingSpinnerWidget(const WaitingSpinnerWidget&);WaitingSpinnerWidget& operator=(const WaitingSpinnerWidget&);QTimer *_timer;bool    _centerOnParent;bool    _disableParentWhenSpinning;int     _currentCounter;bool    _isSpinning;
};
// waitingspinnerwidget.cpp/* Original Work Copyright (c) 2012-2014 Alexander TurkinModified 2014 by William HallattModified 2015 by Jacob DawidPermission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/// Own includes
#include "waitingspinnerwidget.h"// Standard includes
#include <cmath>
#include <algorithm>// Qt includes
#include <QPainter>
#include <QTimer>WaitingSpinnerWidget::WaitingSpinnerWidget(QWidget *parent,bool centerOnParent,bool disableParentWhenSpinning): QWidget(parent),_centerOnParent(centerOnParent),_disableParentWhenSpinning(disableParentWhenSpinning) {initialize();
}WaitingSpinnerWidget::WaitingSpinnerWidget(Qt::WindowModality modality,QWidget *parent,bool centerOnParent,bool disableParentWhenSpinning): QWidget(parent, Qt::Dialog | Qt::FramelessWindowHint),_centerOnParent(centerOnParent),_disableParentWhenSpinning(disableParentWhenSpinning){initialize();// We need to set the window modality AFTER we've hidden the// widget for the first time since changing this property while// the widget is visible has no effect.setWindowModality(modality);setAttribute(Qt::WA_TranslucentBackground);
}void WaitingSpinnerWidget::initialize() {_color = Qt::black;_roundness = 100.0;_minimumTrailOpacity = 3.14159265358979323846;_trailFadePercentage = 80.0;_revolutionsPerSecond = 1.57079632679489661923;_numberOfLines = 20;_lineLength = 10;_lineWidth = 2;_innerRadius = 10;_currentCounter = 0;_isSpinning = false;_timer = new QTimer(this);connect(_timer, SIGNAL(timeout()), this, SLOT(rotate()));updateSize();updateTimer();hide();
}void WaitingSpinnerWidget::paintEvent(QPaintEvent *) {updatePosition();QPainter painter(this);painter.fillRect(this->rect(), Qt::transparent);painter.setRenderHint(QPainter::Antialiasing, true);if (_currentCounter >= _numberOfLines) {_currentCounter = 0;}painter.setPen(Qt::NoPen);for (int i = 0; i < _numberOfLines; ++i) {painter.save();painter.translate(_innerRadius + _lineLength,_innerRadius + _lineLength);qreal rotateAngle =static_cast<qreal>(360 * i) / static_cast<qreal>(_numberOfLines);painter.rotate(rotateAngle);painter.translate(_innerRadius, 0);int distance =lineCountDistanceFromPrimary(i, _currentCounter, _numberOfLines);QColor color =currentLineColor(distance, _numberOfLines, _trailFadePercentage,_minimumTrailOpacity, _color);painter.setBrush(color);// TODO improve the way rounded rect is paintedpainter.drawRoundedRect(QRect(0, -_lineWidth / 2, _lineLength, _lineWidth), _roundness,_roundness, Qt::RelativeSize);painter.restore();}
}void WaitingSpinnerWidget::start() {updatePosition();_isSpinning = true;show();if(parentWidget() && _disableParentWhenSpinning) {parentWidget()->setEnabled(false);}if (!_timer->isActive()) {_timer->start();_currentCounter = 0;}
}void WaitingSpinnerWidget::stop() {_isSpinning = false;hide();if(parentWidget() && _disableParentWhenSpinning) {parentWidget()->setEnabled(true);}if (_timer->isActive()) {_timer->stop();_currentCounter = 0;}
}void WaitingSpinnerWidget::setNumberOfLines(int lines) {_numberOfLines = lines;_currentCounter = 0;updateTimer();
}void WaitingSpinnerWidget::setLineLength(int length) {_lineLength = length;updateSize();
}void WaitingSpinnerWidget::setLineWidth(int width) {_lineWidth = width;updateSize();
}void WaitingSpinnerWidget::setInnerRadius(int radius) {_innerRadius = radius;updateSize();
}QColor WaitingSpinnerWidget::color() {return _color;
}qreal WaitingSpinnerWidget::roundness() {return _roundness;
}qreal WaitingSpinnerWidget::minimumTrailOpacity() {return _minimumTrailOpacity;
}qreal WaitingSpinnerWidget::trailFadePercentage() {return _trailFadePercentage;
}qreal WaitingSpinnerWidget::revolutionsPersSecond() {return _revolutionsPerSecond;
}int WaitingSpinnerWidget::numberOfLines() {return _numberOfLines;
}int WaitingSpinnerWidget::lineLength() {return _lineLength;
}int WaitingSpinnerWidget::lineWidth() {return _lineWidth;
}int WaitingSpinnerWidget::innerRadius() {return _innerRadius;
}bool WaitingSpinnerWidget::isSpinning() const {return _isSpinning;
}void WaitingSpinnerWidget::setRoundness(qreal roundness) {_roundness = std::max(0.0, std::min(100.0, roundness));
}void WaitingSpinnerWidget::setColor(QColor color) {_color = color;
}void WaitingSpinnerWidget::setRevolutionsPerSecond(qreal revolutionsPerSecond) {_revolutionsPerSecond = revolutionsPerSecond;updateTimer();
}void WaitingSpinnerWidget::setTrailFadePercentage(qreal trail) {_trailFadePercentage = trail;
}void WaitingSpinnerWidget::setMinimumTrailOpacity(qreal minimumTrailOpacity) {_minimumTrailOpacity = minimumTrailOpacity;
}void WaitingSpinnerWidget::rotate() {++_currentCounter;if (_currentCounter >= _numberOfLines) {_currentCounter = 0;}update();
}void WaitingSpinnerWidget::updateSize() {int size = (_innerRadius + _lineLength) * 2;setFixedSize(size, size);
}void WaitingSpinnerWidget::updateTimer() {_timer->setInterval(1000 / (_numberOfLines * _revolutionsPerSecond));
}void WaitingSpinnerWidget::updatePosition() {if (parentWidget() && _centerOnParent) {move(parentWidget()->width() / 2 - width() / 2,parentWidget()->height() / 2 - height() / 2);}
}int WaitingSpinnerWidget::lineCountDistanceFromPrimary(int current, int primary,int totalNrOfLines) {int distance = primary - current;if (distance < 0) {distance += totalNrOfLines;}return distance;
}QColor WaitingSpinnerWidget::currentLineColor(int countDistance, int totalNrOfLines,qreal trailFadePerc, qreal minOpacity,QColor color) {if (countDistance == 0) {return color;}const qreal minAlphaF = minOpacity / 100.0;int distanceThreshold =static_cast<int>(ceil((totalNrOfLines - 1) * trailFadePerc / 100.0));if (countDistance > distanceThreshold) {color.setAlphaF(minAlphaF);} else {qreal alphaDiff = color.alphaF() - minAlphaF;qreal gradient = alphaDiff / static_cast<qreal>(distanceThreshold + 1);qreal resultAlpha = color.alphaF() - gradient * countDistance;// If alpha is out of bounds, clip it.resultAlpha = std::min(1.0, std::max(0.0, resultAlpha));color.setAlphaF(resultAlpha);}return color;
}

三、祝愿

本章代码小而美,生活中也有无数个小美好。
祝愿朋友们:新年一路向上!事业永不卡顿!共赴美好,开启新征程~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/592600.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux 进程(五) 调度与切换

概念准备 当一个进程放在cpu上运行时&#xff0c;是必须要把进程的代码跑完才会进行下一个进程吗&#xff1f;答案肯定是 不对。现在的操作系统都是基于时间片轮转执行的。 时间片&#xff08;timeslice&#xff09;又称为“量子&#xff08;quantum&#xff09;”或“处理器片…

计算机网络【Cookie和session机制】

会话&#xff08;Session&#xff09;跟踪是Web程序中常用的技术&#xff0c;用来跟踪用户的整个会话。常用的会话跟踪技术是Cookie与Session。Cookie通过在客户端记录信息确定用户身份&#xff0c;Session通过在服务器端记录信息确定用户身份。 本章将系统地讲述Cookie与Sess…

【Pytorch】学习记录分享11——PyTorch GAN对抗生成网络

PyTorch GAN对抗生成网络 0. 工程实现1. GAN对抗生成网络结构2. GAN 构造损失函数&#xff08;LOSS&#xff09;3. GAN对抗生成网络LOSS损失函数说明 0. 工程实现 1. GAN对抗生成网络结构 2. GAN 构造损失函数&#xff08;LOSS&#xff09; LOSS公式与含义&#xff1a; LOSS…

javascript 常见工具函数(四)

31.RGB值和十六进制值之间的转换&#xff1a; &#xff08;1&#xff09;十六进制的颜色转为 RGB格式&#xff1a; /*16进制颜色转为RGB格式*/String.prototype.colorRgb function () {var sColor this.toLowerCase();if (sColor && reg.test(sColor)) {if (sColor.l…

C++初阶——类与对象

目录 C宏函数 在使用宏函数时&#xff0c;有几个常见的错误需要注意&#xff1a; 宏函数在某些情况下有以下优势&#xff1a; 1.C宏函数 在 C 中&#xff0c;宏函数&#xff08;Macro Function&#xff09;是使用预处理器定义的宏&#xff08;Macro&#xff09;&#xff0…

初识Linux下进程

&#x1f30e;初识进程 初识进程 简单认识一下进程 如何管理进程 进程属性信息 内核运行队列 查看进程 通过系统调用获取进程标识符       父子进程       查看运行中的进程 总结 前言&#xff1a; 我们在电脑上点开的一个个应用&#xff0c;其实就是一个个进程&am…

初识Java并发,一问读懂Java并发知识文集(4)

&#x1f3c6;作者简介&#xff0c;普修罗双战士&#xff0c;一直追求不断学习和成长&#xff0c;在技术的道路上持续探索和实践。 &#x1f3c6;多年互联网行业从业经验&#xff0c;历任核心研发工程师&#xff0c;项目技术负责人。 &#x1f389;欢迎 &#x1f44d;点赞✍评论…

智能标志桩:防盗防外物入侵_图像监测_态势感知_深圳鼎信

智能标志桩是一种新型的智能化标志设备&#xff0c;主要用于标识地下管道的位置、类型等&#xff0c;起警示作用。这与传统的标志桩大不相同&#xff0c;物联网的高速发展赋予了智能标志桩科技的力量&#xff0c;使它可以连接互联网&#xff0c;还具备图像监控的功能&#xff0…

2024年P气瓶充装证考试题库及P气瓶充装试题解析

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2024年P气瓶充装证考试题库及P气瓶充装试题解析是安全生产模拟考试一点通结合&#xff08;安监局&#xff09;特种作业人员操作证考试大纲和&#xff08;质检局&#xff09;特种设备作业人员上岗证考试大纲随机出的P气…

C++Qt6 多种排序算法的比较 数据结构课程设计 | JorbanS

一、 问题描述 在计算机科学与数学中&#xff0c;一个排序算法&#xff08;英语&#xff1a;Sorting algorithm&#xff09;是一种能将一串资料依照特定排序方式排列的算法。最常用到的排序方式是数值顺序以及字典顺序。有效的排序算法在一些算法&#xff08;例如搜索算法与合…

Linux系统操作常用指令

打开终端&#xff1a; ctrlshiftt:切换标签 ctrlshiftn:新增窗口 Linux命令大全(超详细版)_第二范式的博客-CSDN博客 VMware运行时以管理员身份运行&#xff0c;可以避免许多问题。 输入法切换 ctrl 空格 放大终端&#xff1a;ctrlshift"" 缩小终端&#xff1a;ctrl“…

【深度学习-基础学习】Transformer 笔记

本篇文章学习总结 李宏毅 2021 Spring 课程中关于 Transformer 相关的内容。课程链接以及PPT&#xff1a;李宏毅Spring2021ML这篇Blog需要Self-Attention为前置知识。 Transfomer 简介 Transfomer 架构主要是用来解决 Seq2Seq 问题的&#xff0c;也就是 Sequence to Sequence…

web前端——clear可以清除浮动产生的影响

clear可以解决高度塌陷的问题&#xff0c;产生的副作用要小 未使用clear之前 <!DOCTYPE html> <head><meta charset"UTF-8"><title>高度塌陷相关学习</title><style>div{font-size:50px;}.box1{width:200px;height:200px;backg…

【已解决】打印PDF文件,如何跳过不需要的页面?

打印PDF文件的时候&#xff0c;有时候我们只需要打印其中的几页&#xff0c;并不需要全部打印&#xff0c;那如何在打印时跳过那些不需要的页面呢&#xff1f;不清楚的小伙伴一起来看看吧&#xff01; 如果你是通过网页打开PDF文件&#xff0c;那么可以在页面中找到并点击“打…

[每周一更]-(第53期):Python3和Django环境安装并搭建Django

Python和Django 的安装 Python和Django 兼容情况 django 1.11.x python 2.7 3.4 3.5 3.6 LTS python 目前在用版本 Python 3.6.5 2018-03-28 更新Python 2.7.15 2018-05-01 更新Python 2.7.5 2013-05-12 更新 python和python3安装pip 同时安装上 python2.7.18、python3.11…

c语言结构体学习上篇

文章目录 前言一、结构体的声明1&#xff0c;什么叫结构体?2&#xff0c;结构体的类型3,结构体变量的创建和初始化4&#xff0c;结构体的类型5&#xff0c;结构体的初始化 二、结构体的访问1&#xff0c;结构体成员的点操作符访问2&#xff0c;结构体体成员的指针访问 前言 昨…

用户管理第2节课--idea 2023.2 后端--实现基本数据库操作(操作user表) -- 自动生成 --【本人】

一、插件安装 1.1 搜索插件 mybatis 安装 1.2 接受安装 1.3 再次进入&#xff0c;说明安装好了 1.4 与鱼皮不同点 1&#xff09;mybatis 版本不一致 鱼皮&#xff1a; 本人&#xff1a; 2&#xff09;鱼皮需重启安装 本人不需要 1.5 【需完成 三、步骤&#xff0c;再来看】 …

Git - 强制替换覆盖 master 分支解决方案

问题描述 在版本迭代中&#xff0c;通常会保持一个主分支 master&#xff0c;及多个 dev 分支&#xff0c;但是因为 dev 分支的开发周期过长&#xff0c;迭代太多而没有及时维护 master &#xff0c;导致后来发版上线的大部分代码都在 dev 分支上&#xff0c;如果将代码在 mas…

LiveGBS流媒体平台GB/T28181功能-用户管理通道权限管理关联通道支持只看已选只看未选添加用户备注角色

LiveGBS功能用户管理通道权限管理关联通道支持只看已选只看未选添加用户备注角色 1、用户管理2、添加用户3、关联通道3.1、只看已选3.2、只看未选 4、自定义角色5、搭建GB28181视频直播平台 1、用户管理 LiveGBS支持用户管理&#xff0c;添加用户&#xff0c;及配置相关用户权…

promise.prototype.finally重写和兼容火狐低版本浏览器

一、finally()方法用于指定不管 Promise 对象最后状态如何&#xff0c;都会执行的操作。该方法是 ES2018 引入标准的 let promise new Promise() promise .then(result > {}) .catch(error > {}) .finally(() > {})finally方法的回调函数不接受任何参数;finally方法…