Qt实现SwitchButton滑动开关按钮组件
概述
使用Qt如何制作一个滑动开关按钮,同类的文章和代码网上很多,但很多都是pyqt编写的,也有c++编写的,大家可以参考. 我这里主要是实现了一个滑动按钮,富有滑动动画和文字,话不多说,上代码
自定义滑动按钮
c++/Qt实现
.h文件
#ifndef SwitchButtonInsideINSIDE_H
#define SwitchButtonInsideINSIDE_H#include <QWidget>#include "customcomponent_global.h"class Slider;class CUSTOMCOMPONENT_EXPORT SwitchButtonInside : public QWidget
{Q_OBJECTpublic:explicit SwitchButtonInside(QWidget *parent = nullptr);~SwitchButtonInside();/*** @brief SetSize 设置按钮的尺寸* @param nWidth 按钮的新宽度* @param nHeight 按钮的新高度*/void SetSize(int nWidth, int nHeight);/*** @brief SetActiveColor 设置按钮激活时候的颜色* @param color 激活颜色*/void SetActiveColor(const QColor& color);/*** @brief SetInactiveColor 设置按钮未激活时候的颜色* @param color 未激活颜色*/void SetInactiveColor(const QColor& color);/*** @brief SetSliderColor 设置滑块颜色* @param color 滑块的颜色*/void SetSliderColor(const QColor& color);/*** @brief SetStatus 设置按钮状态* @param bActive true: 激活,false: 未激活*/void SetStatus(bool bActive);/*** @brief GetStatus 获取按钮当前状态* @return true: 激活,false: 未激活*/bool GetStatus() const;/*** @brief SetStatus 设置按钮显示文字* @param text: 文字内容*/void SetText(const QString &text);protected:void paintEvent(QPaintEvent *event) override;void mousePressEvent(QMouseEvent *event) override;void mouseReleaseEvent(QMouseEvent *event) override;void ToActive();void ToInactive();private:bool m_bActive; // 是否激活int m_nArcRadius; // 圆弧的半径int m_nRectWidth; // 矩形的宽度const short m_nMargin = 2;const int m_nDuration = 100; // 动画时间,单位毫秒bool m_bClicked; // 能否被点击。如果动画还没结束,无法进行点击/状态切换QColor m_colorActive; // 激活时的颜色QColor m_colorInactive;Slider* m_pSlider;QString m_text; // 显示文字signals:/*** @brief Clicked 按钮被点击后发出的信号* @param status 当前按钮状态。true为active,false为inactive*/void Clicked(bool status);
};class Slider : public QWidget
{Q_OBJECT
public:explicit Slider(QWidget* parent = nullptr);~Slider();/*** @brief SetSliderColor 设置滑块颜色* @param color*/void SetSliderColor(const QColor& color);protected:void paintEvent(QPaintEvent* e) override;private:QColor m_sliderColor;
};#endif // SwitchButtonInsideINSIDE_H
.cpp文件
#include "switchbuttoninside.h"
#include <QPainter>
#include <QFont>
#include <QPainterPath>
#include <QPropertyAnimation>SwitchButtonInside::SwitchButtonInside(QWidget *parent) :QWidget(parent)
{resize(72, 28); // 默认80,28宽高m_pSlider = new Slider(this);m_pSlider->resize(height() - m_nMargin * 2, height() - m_nMargin * 2);m_pSlider->move(m_nMargin, m_nMargin);m_bActive = false; // 默认未激活m_nArcRadius = std::min(width(), height()); // 默认半径m_nRectWidth = width() - m_nArcRadius;m_colorActive = qRgb(60, 189, 136);m_colorInactive = qRgb(167, 177, 188);
}SwitchButtonInside::~SwitchButtonInside()
{
}void SwitchButtonInside::SetSize(int nWidth, int nHeight)
{resize(nWidth, nHeight);m_pSlider->resize(height() - m_nMargin * 2, height() - m_nMargin * 2);m_pSlider->move(m_nMargin, m_nMargin);m_nArcRadius = std::min(width(), height());m_nRectWidth = width() - m_nArcRadius;
}void SwitchButtonInside::SetActiveColor(const QColor& color)
{m_colorActive = color;
}void SwitchButtonInside::SetInactiveColor(const QColor& color)
{m_colorInactive = color;
}void SwitchButtonInside::SetSliderColor(const QColor& color)
{m_pSlider->SetSliderColor(color);
}void SwitchButtonInside::SetStatus(bool bActive)
{if(m_bActive == bActive) {return;}m_bActive = bActive;if(m_bActive) {ToActive();} else {ToInactive();}
}bool SwitchButtonInside::GetStatus() const
{return m_bActive;
}void SwitchButtonInside::SetText(const QString &text)
{m_text = text;
}void SwitchButtonInside::paintEvent(QPaintEvent *)
{qDebug() << "[SwitchButtonInside]m_nArcRadius = " << m_nArcRadius<< "| m_nRectWidth << " << m_nRectWidth<< "| size = " << width() << "," << height();if (m_nArcRadius > height()) {qDebug() << "******* switchbutton resize ******";SetSize(width(), height());}QPainter p;p.begin(this);p.setRenderHint(QPainter::Antialiasing, true);p.setPen(Qt::NoPen);if(m_bActive) p.setBrush(QBrush(m_colorActive));else p.setBrush(QBrush(m_colorInactive));QPainterPath leftPath;leftPath.addEllipse(0, 0, m_nArcRadius, m_nArcRadius);QPainterPath middlePath;middlePath.addRect(m_nArcRadius / 2, 0, m_nRectWidth, m_nArcRadius);QPainterPath rightPath;rightPath.addEllipse(m_nRectWidth, 0, m_nArcRadius, m_nArcRadius);QPainterPath path = leftPath + middlePath + rightPath;p.drawPath(path);QPen pen;pen.setColor(Qt::white);p.setPen(pen);QFont ft;ft.setPointSize(9);p.setFont(ft);if (m_bActive) {p.drawText(QRect(0, 0, m_nRectWidth,m_nArcRadius), Qt::AlignCenter, m_text);} else {p.drawText(QRect(m_nArcRadius, 0,m_nRectWidth, m_nArcRadius), Qt::AlignCenter, m_text);}p.end();
}void SwitchButtonInside::mousePressEvent(QMouseEvent *event)
{QWidget::mousePressEvent(event);
}void SwitchButtonInside::mouseReleaseEvent(QMouseEvent *event)
{emit Clicked(!m_bActive);QWidget::mouseReleaseEvent(event);
}void SwitchButtonInside::ToActive()
{QPropertyAnimation* pAnimation = new QPropertyAnimation(m_pSlider, "geometry");pAnimation->setDuration(m_nDuration);pAnimation->setStartValue(m_pSlider->rect());pAnimation->setEndValue(QRect(width() - m_pSlider->width() - m_nMargin,m_nMargin,m_pSlider->width(),m_pSlider->height()));connect(pAnimation, &QPropertyAnimation::valueChanged, this, [&](const QVariant &value){Q_UNUSED(value)update();});pAnimation->start(QAbstractAnimation::DeleteWhenStopped);
}void SwitchButtonInside::ToInactive()
{QPropertyAnimation* pAnimation = new QPropertyAnimation(m_pSlider, "geometry");pAnimation->setDuration(m_nDuration);pAnimation->setStartValue(QRect(m_pSlider->x(),m_pSlider->y(),m_pSlider->width(),m_pSlider->height()));pAnimation->setEndValue(QRect(m_nMargin,m_nMargin,m_pSlider->width(),m_pSlider->height()));connect(pAnimation, &QPropertyAnimation::valueChanged, this, [&](const QVariant &value){Q_UNUSED(value)update();});pAnimation->start(QAbstractAnimation::DeleteWhenStopped);
}///
/// Slider 滑块类 //
//Slider::Slider(QWidget *parent) : QWidget(parent)
{m_sliderColor = Qt::white;resize(56, 56);
}Slider::~Slider()
{}void Slider::SetSliderColor(const QColor &color)
{m_sliderColor = color;update();
}void Slider::paintEvent(QPaintEvent *e)
{QPainter p(this);p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);p.fillRect(rect(), Qt::transparent);p.setBrush(m_sliderColor);p.setPen(Qt::NoPen);p.drawRoundedRect(rect(), width() / 2, height() / 2);QWidget::paintEvent(e);
}
相关文章:
Qt实现SwitchButton滑动开关按钮组件
概述 使用Qt如何制作一个滑动开关按钮,同类的文章和代码网上很多,但很多都是pyqt编写的,也有c编写的,大家可以参考. 我这里主要是实现了一个滑动按钮,富有滑动动画和文字,话不多说,上代码 自定义…...
C++进阶:继承
文章目录 继承的概念继承的定义方式继承关系和访问限定符基类和派生类对象的赋值转换继承中的作用域派生类中的默认成员函数构造函数拷贝构造函数赋值拷贝函数析构函数 总结 继承的概念 继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段,它允…...
SFTP工具
SFTP工具 工具类配置类调用 工具类 Slf4j Component public class SFTPUtils {Resourceprivate SftpConfig sftpConfig;Session session null;Channel channel null;/*** 网络图片url** param fileUrl* throws JSchException*/public String uploadFileSFTP(String fileUrl) …...
服务器数据恢复—vxfs文件系统元数据被破坏的数据恢复案例
服务器存储数据恢复环境: 某品牌MSA2000服务器存储中有一组由8块SAS硬盘组建的raid5磁盘阵列,其中包含一块热备盘。分配了6个LUN,均分配给HP-Unix小机使用。磁盘分区由LVM进行管理,存放的数据主要为Oracle数据库及OA服务端。 服务…...
【SCAU数据挖掘】数据挖掘期末总复习题库简答题及解析——上
1.K-Means 假定我们对A、B、C、D四个样品分别测量两个变量,得到的结果见下表。 样品 变量 X1X2 A 5 3 B -1 1 C 1 -2 D -3 -2 利用K-Means方法将以上的样品聚成两类。为了实施均值法(K-Means)聚类,首先将这些样品随意分成两类(A、B)和(C、…...
云时代的Java:在云环境中实施Java的最佳实践
引言 云计算已经成为现代软件开发不可或缺的一部分,它提供了灵活性、可扩展性和成本效益。对于Java开发者来说,掌握在云环境中部署和管理Java应用的最佳实践是至关重要的。本文将探讨一些关键策略,帮助你最大化Java在云平台上的性能和效率。…...
STL - 常用算法
概述: 算法主要是由头文件<algorithm><functional><numeric>组成<algorithm>是所有STL头文件中最大的一个,范围涉及比较、 交换、查找、遍历操作、复制、修改等等<numeric>体积很小,只包括几个在序列上面进行…...
Qt | QTextStream 类(文本流)
01、字符编码 1、怎样将字符转换为二进制形式进行存储,存在一个编码的问题,通常都需进行两次编码, 2、字符集:字符的第一次编码是将字符编码为与一个数值(如一个 10 进制整数)相对应,比如把字符 A 编码为 10 进制的 65,B 编码为 66 等。把每一个字符都编码为与一个数值…...
Python学习笔记7:入门知识(七)
前言 之前说过我更换了新的学习路线,现在是根据官方文档和书籍Python crash course来进行学习的,在目前的学习中,对于之前的知识有一些遗漏,这里进行补充。 学习资料有两个,书籍中文版PDF,关注我私信发送…...
如何翻译和本地化游戏?翻译访谈
如何翻译和本地化游戏?这个过程的技术细节有哪些?游戏翻译不同于电影翻译。Logrus IT游戏本地化部门负责人阿列克谢费奥多罗夫(Alexey Fedorov)在接受RUDN语言学系外语系教授和研究人员的采访时谈到了这一点,他是由尤利…...
[C++] 从零实现一个ping服务
💻文章目录 前言ICMP概念报文格式 Ping服务实现系统调用函数具体实现运行测试 总结 前言 ping命令,因为其简单、易用等特点,几乎所有的操作系统都内置了一个ping命令。如果你是一名C初学者,对网络编程、系统编程有所了解ÿ…...
2024网络安全学习路线 非常详细 推荐学习
关键词:网络安全入门、渗透测试学习、零基础学安全、网络安全学习路线 首先咱们聊聊,学习网络安全方向通常会有哪些问题 1、打基础时间太长 学基础花费很长时间,光语言都有几门,有些人会倒在学习 linux 系统及命令的路上&#…...
STM32F103ZET6_HAL_CAN
1定义时钟 2定义按键 按键上拉电阻 3开启串口 4打开CAN(具体什么意思上一篇讲了) 5生成代码 /* USER CODE BEGIN Header */ /********************************************************************************* file : main.c* brief …...
javaWeb项目-ssm+vue网上租车系统功能介绍
本项目源码:java-基于ssmvue的网上租车系统源码说明文档资料资源-CSDN文库 项目关键技术 开发工具:IDEA 、Eclipse 编程语言: Java 数据库: MySQL5.7 框架:ssm、Springboot 前端:Vue、ElementUI 关键技术:springboot、…...
Go模板页面浏览器显示HTML源码问题
<!--* Title: This is a file for ……* Author: JackieZheng* Date: 2024-06-09 17:00:01* LastEditTime: 2024-06-09 17:01:12* LastEditors: Please set LastEditors* Description:* FilePath: \\GoCode\\templates\\index.html --> <!DOCTYPE html> <html …...
弃用Docker Desktop:在WSL2中玩转Docker之Docker Engine 部署与WSL入门
Docker技术概论 在WSL2中玩转Docker之Docker Engine部署 - 文章信息 - Author: 李俊才 (jcLee95) Visit me at CSDN: https://jclee95.blog.csdn.netMy WebSite:http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this article:https://bl…...
Mac下载了docker,在终端使用docker命令时用不了
问题:在mac使用docker的时候,拉取docker镜像失败 原因:docker是需要用app使用的 ,所以在使用的时候必须打开这个桌面端软件才可以在终端上使用docker命令!!!...
Spring Security——基于MyBatis
目录 项目总结 新建一个项目 pom.xml application.properties配置文件 User实体类 UserMapper映射接口 UserService访问数据库中的用户信息 WebSecurityConfig配置类 MyAuthenticationFailureHandler登录失败后 MyAuthenticationSuccessHandlerw登录成功后 WebSecur…...
Qt——升级系列(Level Four):控件概述、QWidget 核心属性、按钮类控件
目录 控件概述 QWidget 核心属性 核心属性概览 enabled geometry windowTitle windowIcon windowOpacity cursor font toolTip focusPolicy styleSheet 按钮类控件 Push Button Radio Buttion Check Box Tool Button 控件概述 Widget 是 Qt 中的核⼼概念. 英⽂原义是 "…...
品质卓越为你打造App UI 风格
品质卓越为你打造App UI 风格...
Python基础语法:生成器 generator(yield)
一、简介根据指定的规则循环生成数据,当条件不成立时则生成数据结束。数据不是一次性全部生成出来,而是使用一个,再生成一个,好处是可以节约大量的内存。就像设计模式中的懒汉式。适合处理大数据或流数。生成器是一种特殊的迭代器…...
Python PIL 画矩形框
基础代码 from PIL import Image, ImageDraw# 打开图片 img Image.open(your_image.jpg)# 创建绘图对象 draw ImageDraw.Draw(img)# 矩形坐标 (x1, y1, x2, y2) coords (23, 21, 69, 76)# 画矩形框(红色,线宽2) draw.rectangle(coords, ou…...
智能体所有权与版权:AI Agent Harness Engineering 创造的作品归谁所有?
1. 标题选项 《AI Agent创作版权迷局破解:从Harness工程原理到所有权划分的完整指南》 《智能体作品归谁?AI Agent Harness Engineering场景下的版权规则深度拆解》 《告别权属纠纷:一文搞懂AI Agent生成内容的所有权、版权与收益分配规则》 《Harness工程视角下的AI创作权:…...
PCL 基于强度的双边滤波【2026最新版】
目录 一、算法原理 1、计算步骤 2、算法源码 3、函数解析 4、参考文献 二、代码实现 三、结果展示 四、滤波后未发生变化的原因 五、解决办法 六、结果展示 七、相关链接 本文由CSDN点云侠原创,博客长期更新,本文最近一次更新时间为:2026年5月24日。 一、算法原理 1、计算…...
基于Netburner NANO54415构建工业级嵌入式Web服务器:从硬件选型到广域监控实战
1. 项目概述:一个为广域与本地监控而生的嵌入式Web服务器如果你正在寻找一个能部署在野外、工厂角落或者任何需要远程数据采集与控制场景下的嵌入式Web服务器方案,并且对市面上那些要么性能孱弱、要么开发门槛极高的开发板感到厌倦,那么这个基…...
从安装到排错:手把手解决Linux服务器上Nacos启动失败的十大常见问题
从安装到排错:手把手解决Linux服务器上Nacos启动失败的十大常见问题当你在Linux服务器上部署Nacos时,是否遇到过启动失败却无从下手的困境?作为阿里巴巴开源的服务发现和配置管理平台,Nacos在微服务架构中扮演着重要角色。然而&am…...
别再只比参数了!从插件生态到中文优化,聊聊ChatGPT和文心一言的“隐形”差异
超越参数之争:ChatGPT与文心一言的生态与本土化实战解析 当技术评测文章还在反复比较模型参数量与发布时间时,真正影响日常工作效率的往往是那些未被量化的"软实力"。本文将从插件生态构建与中文场景优化两个维度,带您重新认识这两…...
英雄联盟回放播放难题终极解决方案:ROFLPlayer完整使用指南
英雄联盟回放播放难题终极解决方案:ROFLPlayer完整使用指南 【免费下载链接】ROFL-Player (No longer supported) One stop shop utility for viewing League of Legends replays! 项目地址: https://gitcode.com/gh_mirrors/ro/ROFL-Player 还在为英雄联盟旧…...
HKMG工艺的“阿喀琉斯之踵”:聊聊那个无法移除的SiON界面层与未来0.3nm的挑战
HKMG工艺的隐形枷锁:SiON界面层的物理宿命与亚纳米级突围战 在半导体工艺演进的史诗中,HKMG(高K金属栅)技术曾被寄予厚望——它用金属栅极替代传统多晶硅,搭配高K介质材料HfO₂,一举解决了栅极耗尽和漏电流…...
Windows 11终极优化指南:一键清理系统,释放51%性能潜力
Windows 11终极优化指南:一键清理系统,释放51%性能潜力 【免费下载链接】Win11Debloat A simple, lightweight PowerShell script that allows you to remove pre-installed apps, disable telemetry, as well as perform various other changes to decl…...
