当前位置: 首页 > news >正文

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如何制作一个滑动开关按钮&#xff0c;同类的文章和代码网上很多&#xff0c;但很多都是pyqt编写的&#xff0c;也有c编写的&#xff0c;大家可以参考. 我这里主要是实现了一个滑动按钮&#xff0c;富有滑动动画和文字&#xff0c;话不多说&#xff0c;上代码 自定义…...

C++进阶:继承

文章目录 继承的概念继承的定义方式继承关系和访问限定符基类和派生类对象的赋值转换继承中的作用域派生类中的默认成员函数构造函数拷贝构造函数赋值拷贝函数析构函数 总结 继承的概念 继承(inheritance)机制是面向对象程序设计使代码可以复用的最重要的手段&#xff0c;它允…...

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文件系统元数据被破坏的数据恢复案例

服务器存储数据恢复环境&#xff1a; 某品牌MSA2000服务器存储中有一组由8块SAS硬盘组建的raid5磁盘阵列&#xff0c;其中包含一块热备盘。分配了6个LUN&#xff0c;均分配给HP-Unix小机使用。磁盘分区由LVM进行管理&#xff0c;存放的数据主要为Oracle数据库及OA服务端。 服务…...

【SCAU数据挖掘】数据挖掘期末总复习题库简答题及解析——上

1.K-Means 假定我们对A、B、C、D四个样品分别测量两个变量&#xff0c;得到的结果见下表。 样品 变量 X1X2 A 5 3 B -1 1 C 1 -2 D -3 -2 利用K-Means方法将以上的样品聚成两类。为了实施均值法(K-Means)聚类&#xff0c;首先将这些样品随意分成两类(A、B)和(C、…...

云时代的Java:在云环境中实施Java的最佳实践

引言 云计算已经成为现代软件开发不可或缺的一部分&#xff0c;它提供了灵活性、可扩展性和成本效益。对于Java开发者来说&#xff0c;掌握在云环境中部署和管理Java应用的最佳实践是至关重要的。本文将探讨一些关键策略&#xff0c;帮助你最大化Java在云平台上的性能和效率。…...

STL - 常用算法

概述&#xff1a; 算法主要是由头文件<algorithm><functional><numeric>组成<algorithm>是所有STL头文件中最大的一个&#xff0c;范围涉及比较、 交换、查找、遍历操作、复制、修改等等<numeric>体积很小&#xff0c;只包括几个在序列上面进行…...

Qt | QTextStream 类(文本流)

01、字符编码 1、怎样将字符转换为二进制形式进行存储,存在一个编码的问题,通常都需进行两次编码, 2、字符集:字符的第一次编码是将字符编码为与一个数值(如一个 10 进制整数)相对应,比如把字符 A 编码为 10 进制的 65,B 编码为 66 等。把每一个字符都编码为与一个数值…...

Python学习笔记7:入门知识(七)

前言 之前说过我更换了新的学习路线&#xff0c;现在是根据官方文档和书籍Python crash course来进行学习的&#xff0c;在目前的学习中&#xff0c;对于之前的知识有一些遗漏&#xff0c;这里进行补充。 学习资料有两个&#xff0c;书籍中文版PDF&#xff0c;关注我私信发送…...

如何翻译和本地化游戏?翻译访谈

如何翻译和本地化游戏&#xff1f;这个过程的技术细节有哪些&#xff1f;游戏翻译不同于电影翻译。Logrus IT游戏本地化部门负责人阿列克谢费奥多罗夫&#xff08;Alexey Fedorov&#xff09;在接受RUDN语言学系外语系教授和研究人员的采访时谈到了这一点&#xff0c;他是由尤利…...

[C++] 从零实现一个ping服务

&#x1f4bb;文章目录 前言ICMP概念报文格式 Ping服务实现系统调用函数具体实现运行测试 总结 前言 ping命令&#xff0c;因为其简单、易用等特点&#xff0c;几乎所有的操作系统都内置了一个ping命令。如果你是一名C初学者&#xff0c;对网络编程、系统编程有所了解&#xff…...

2024网络安全学习路线 非常详细 推荐学习

关键词&#xff1a;网络安全入门、渗透测试学习、零基础学安全、网络安全学习路线 首先咱们聊聊&#xff0c;学习网络安全方向通常会有哪些问题 1、打基础时间太长 学基础花费很长时间&#xff0c;光语言都有几门&#xff0c;有些人会倒在学习 linux 系统及命令的路上&#…...

STM32F103ZET6_HAL_CAN

1定义时钟 2定义按键 按键上拉电阻 3开启串口 4打开CAN&#xff08;具体什么意思上一篇讲了&#xff09; 5生成代码 /* USER CODE BEGIN Header */ /********************************************************************************* file : main.c* brief …...

javaWeb项目-ssm+vue网上租车系统功能介绍

本项目源码&#xff1a;java-基于ssmvue的网上租车系统源码说明文档资料资源-CSDN文库 项目关键技术 开发工具&#xff1a;IDEA 、Eclipse 编程语言: Java 数据库: MySQL5.7 框架&#xff1a;ssm、Springboot 前端&#xff1a;Vue、ElementUI 关键技术&#xff1a;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&#xff1a;http://thispage.tech/Email: 291148484163.com. Shenzhen ChinaAddress of this article:https://bl…...

Mac下载了docker,在终端使用docker命令时用不了

问题&#xff1a;在mac使用docker的时候&#xff0c;拉取docker镜像失败 原因&#xff1a;docker是需要用app使用的 &#xff0c;所以在使用的时候必须打开这个桌面端软件才可以在终端上使用docker命令&#xff01;&#xff01;&#xff01;...

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 风格...

css实现圆环展示百分比,根据值动态展示所占比例

代码如下 <view class""><view class"circle-chart"><view v-if"!!num" class"pie-item" :style"{background: conic-gradient(var(--one-color) 0%,#E9E6F1 ${num}%),}"></view><view v-else …...

ubuntu搭建nfs服务centos挂载访问

在Ubuntu上设置NFS服务器 在Ubuntu上&#xff0c;你可以使用apt包管理器来安装NFS服务器。打开终端并运行&#xff1a; sudo apt update sudo apt install nfs-kernel-server创建共享目录 创建一个目录用于共享&#xff0c;例如/shared&#xff1a; sudo mkdir /shared sud…...

相机Camera日志实例分析之二:相机Camx【专业模式开启直方图拍照】单帧流程日志详解

【关注我&#xff0c;后续持续新增专题博文&#xff0c;谢谢&#xff01;&#xff01;&#xff01;】 上一篇我们讲了&#xff1a; 这一篇我们开始讲&#xff1a; 目录 一、场景操作步骤 二、日志基础关键字分级如下 三、场景日志如下&#xff1a; 一、场景操作步骤 操作步…...

8k长序列建模,蛋白质语言模型Prot42仅利用目标蛋白序列即可生成高亲和力结合剂

蛋白质结合剂&#xff08;如抗体、抑制肽&#xff09;在疾病诊断、成像分析及靶向药物递送等关键场景中发挥着不可替代的作用。传统上&#xff0c;高特异性蛋白质结合剂的开发高度依赖噬菌体展示、定向进化等实验技术&#xff0c;但这类方法普遍面临资源消耗巨大、研发周期冗长…...

线程同步:确保多线程程序的安全与高效!

全文目录&#xff1a; 开篇语前序前言第一部分&#xff1a;线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分&#xff1a;synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分&#xff…...

vscode(仍待补充)

写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh&#xff1f; debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...

【解密LSTM、GRU如何解决传统RNN梯度消失问题】

解密LSTM与GRU&#xff1a;如何让RNN变得更聪明&#xff1f; 在深度学习的世界里&#xff0c;循环神经网络&#xff08;RNN&#xff09;以其卓越的序列数据处理能力广泛应用于自然语言处理、时间序列预测等领域。然而&#xff0c;传统RNN存在的一个严重问题——梯度消失&#…...

剑指offer20_链表中环的入口节点

链表中环的入口节点 给定一个链表&#xff0c;若其中包含环&#xff0c;则输出环的入口节点。 若其中不包含环&#xff0c;则输出null。 数据范围 节点 val 值取值范围 [ 1 , 1000 ] [1,1000] [1,1000]。 节点 val 值各不相同。 链表长度 [ 0 , 500 ] [0,500] [0,500]。 …...

C# 类和继承(抽象类)

抽象类 抽象类是指设计为被继承的类。抽象类只能被用作其他类的基类。 不能创建抽象类的实例。抽象类使用abstract修饰符声明。 抽象类可以包含抽象成员或普通的非抽象成员。抽象类的成员可以是抽象成员和普通带 实现的成员的任意组合。抽象类自己可以派生自另一个抽象类。例…...

【RockeMQ】第2节|RocketMQ快速实战以及核⼼概念详解(二)

升级Dledger高可用集群 一、主从架构的不足与Dledger的定位 主从架构缺陷 数据备份依赖Slave节点&#xff0c;但无自动故障转移能力&#xff0c;Master宕机后需人工切换&#xff0c;期间消息可能无法读取。Slave仅存储数据&#xff0c;无法主动升级为Master响应请求&#xff…...