当前位置: 首页 > 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 风格...

浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)

✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义&#xff08;Task Definition&…...

golang循环变量捕获问题​​

在 Go 语言中&#xff0c;当在循环中启动协程&#xff08;goroutine&#xff09;时&#xff0c;如果在协程闭包中直接引用循环变量&#xff0c;可能会遇到一个常见的陷阱 - ​​循环变量捕获问题​​。让我详细解释一下&#xff1a; 问题背景 看这个代码片段&#xff1a; fo…...

shell脚本--常见案例

1、自动备份文件或目录 2、批量重命名文件 3、查找并删除指定名称的文件&#xff1a; 4、批量删除文件 5、查找并替换文件内容 6、批量创建文件 7、创建文件夹并移动文件 8、在文件夹中查找文件...

DockerHub与私有镜像仓库在容器化中的应用与管理

哈喽&#xff0c;大家好&#xff0c;我是左手python&#xff01; Docker Hub的应用与管理 Docker Hub的基本概念与使用方法 Docker Hub是Docker官方提供的一个公共镜像仓库&#xff0c;用户可以在其中找到各种操作系统、软件和应用的镜像。开发者可以通过Docker Hub轻松获取所…...

STM32标准库-DMA直接存储器存取

文章目录 一、DMA1.1简介1.2存储器映像1.3DMA框图1.4DMA基本结构1.5DMA请求1.6数据宽度与对齐1.7数据转运DMA1.8ADC扫描模式DMA 二、数据转运DMA2.1接线图2.2代码2.3相关API 一、DMA 1.1简介 DMA&#xff08;Direct Memory Access&#xff09;直接存储器存取 DMA可以提供外设…...

HubSpot推出与ChatGPT的深度集成引发兴奋与担忧

上周三&#xff0c;HubSpot宣布已构建与ChatGPT的深度集成&#xff0c;这一消息在HubSpot用户和营销技术观察者中引发了极大的兴奋&#xff0c;但同时也存在一些关于数据安全的担忧。 许多网络声音声称&#xff0c;这对SaaS应用程序和人工智能而言是一场范式转变。 但向任何技…...

Modbus RTU与Modbus TCP详解指南

目录 1. Modbus协议基础 1.1 什么是Modbus? 1.2 Modbus协议历史 1.3 Modbus协议族 1.4 Modbus通信模型 🎭 主从架构 🔄 请求响应模式 2. Modbus RTU详解 2.1 RTU是什么? 2.2 RTU物理层 🔌 连接方式 ⚡ 通信参数 2.3 RTU数据帧格式 📦 帧结构详解 🔍…...

【无标题】湖北理元理律师事务所:债务优化中的生活保障与法律平衡之道

文/法律实务观察组 在债务重组领域&#xff0c;专业机构的核心价值不仅在于减轻债务数字&#xff0c;更在于帮助债务人在履行义务的同时维持基本生活尊严。湖北理元理律师事务所的服务实践表明&#xff0c;合法债务优化需同步实现三重平衡&#xff1a; 法律刚性&#xff08;债…...

二维FDTD算法仿真

二维FDTD算法仿真&#xff0c;并带完全匹配层&#xff0c;输入波形为高斯波、平面波 FDTD_二维/FDTD.zip , 6075 FDTD_二维/FDTD_31.m , 1029 FDTD_二维/FDTD_32.m , 2806 FDTD_二维/FDTD_33.m , 3782 FDTD_二维/FDTD_34.m , 4182 FDTD_二维/FDTD_35.m , 4793...

WEB3全栈开发——面试专业技能点P4数据库

一、mysql2 原生驱动及其连接机制 概念介绍 mysql2 是 Node.js 环境中广泛使用的 MySQL 客户端库&#xff0c;基于 mysql 库改进而来&#xff0c;具有更好的性能、Promise 支持、流式查询、二进制数据处理能力等。 主要特点&#xff1a; 支持 Promise / async-await&#xf…...