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

.Net框架,除了EF还有很多很多......

文章目录 1. 引言2. Dapper2.1 概述与设计原理2.2 核心功能与代码示例基本查询多映射查询存储过程调用 2.3 性能优化原理2.4 适用场景 3. NHibernate3.1 概述与架构设计3.2 映射配置示例Fluent映射XML映射 3.3 查询示例HQL查询Criteria APILINQ提供程序 3.4 高级特性3.5 适用场…...

OD 算法题 B卷【正整数到Excel编号之间的转换】

文章目录 正整数到Excel编号之间的转换 正整数到Excel编号之间的转换 excel的列编号是这样的&#xff1a;a b c … z aa ab ac… az ba bb bc…yz za zb zc …zz aaa aab aac…; 分别代表以下的编号1 2 3 … 26 27 28 29… 52 53 54 55… 676 677 678 679 … 702 703 704 705;…...

MySQL的pymysql操作

本章是MySQL的最后一章&#xff0c;MySQL到此完结&#xff0c;下一站Hadoop&#xff01;&#xff01;&#xff01; 这章很简单&#xff0c;完整代码在最后&#xff0c;详细讲解之前python课程里面也有&#xff0c;感兴趣的可以往前找一下 一、查询操作 我们需要打开pycharm …...

智能职业发展系统:AI驱动的职业规划平台技术解析

智能职业发展系统&#xff1a;AI驱动的职业规划平台技术解析 引言&#xff1a;数字时代的职业革命 在当今瞬息万变的就业市场中&#xff0c;传统的职业规划方法已无法满足个人和企业的需求。据统计&#xff0c;全球每年有超过2亿人面临职业转型困境&#xff0c;而企业也因此遭…...

02.运算符

目录 什么是运算符 算术运算符 1.基本四则运算符 2.增量运算符 3.自增/自减运算符 关系运算符 逻辑运算符 &&&#xff1a;逻辑与 ||&#xff1a;逻辑或 &#xff01;&#xff1a;逻辑非 短路求值 位运算符 按位与&&#xff1a; 按位或 | 按位取反~ …...

react更新页面数据,操作页面,双向数据绑定

// 路由不是组件的直接跳转use client&#xff0c;useEffect&#xff0c;useRouter&#xff0c;需3个结合&#xff0c; use client表示客户端 use client; import { Button,Card, Space,Tag,Table,message,Input } from antd; import { useEffect,useState } from react; impor…...

智能照明系统:具备认知能力的“光神经网络”

智能照明系统是物联网技术与传统照明深度融合的产物&#xff0c;其本质是通过感知环境、解析需求、自主决策的闭环控制&#xff0c;重构光与人、空间、环境的关系。这一系统由智能光源、多维传感器、边缘计算单元及云端管理平台构成&#xff0c;形成具备认知能力的“光神经网络…...

LeetCode 2894.分类求和并作差

目录 题目&#xff1a; 题目描述&#xff1a; 题目链接&#xff1a; 思路&#xff1a; 思路一详解&#xff08;遍历 判断&#xff09;&#xff1a; 思路二详解&#xff08;数学规律/公式&#xff09;&#xff1a; 代码&#xff1a; Java思路一&#xff08;遍历 判断&a…...

NLP常用工具包

✨做一次按NLP项目常见工具的使用拆解 1. tokenizer from torchtext.data.utils import get_tokenizertokenizer get_tokenizer(basic_english) text_sample "Were going on an adventure! The weather is really nice today." tokens tokenizer(text_sample) p…...

Server - 使用 Docker 配置 PyTorch 研发环境

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/148421901 免责声明&#xff1a;本文来源于个人知识与公开资料&#xff0c;仅用于学术交流&#xff0c;欢迎讨论&#xff0c;不支持转载。 建议使…...