【Python_PySide6学习笔记(三十八)】基于QPushButton实现自定义的圆形按键指示灯类tQCircularButton

基于QPushButton实现自定义的圆形按键指示灯类tQCircularButton

基于QPushButton实现自定义的圆形按键指示灯类tQCircularButton

前言

在 GUI 界面开发中,我们经常会用到圆形按键指示灯来做提示,在 PyQt 中没有这样的类可以直接使用,所以本文介绍一种方法,基于 QPushButton 实现自定义的圆形按键指示灯类,最终实现如下图所示:

正文

1、Qt样式表

1.1 Qt样式表

PySide 中的 Qt 样式表(Qt Style Sheets,简称 QSS)是一种强大的机制,允许开发者自定义 Qt 应用程序中窗口小部件(widgets)的外观。QSS 的概念和语法在很大程度上受到 HTML 级联样式表(CSS)的启发,但专为 Qt 应用程序中的小部件设计。

1.2 样式属性

QSS 支持多种样式属性,以下是一些常用的属性:

  • 背景background-colorbackground-imagebackground-repeat 等,用于设置小部件的背景;
  • 边框borderborder-styleborder-widthborder-color 等,用于设置小部件的边框样式;
  • 字体font-familyfont-sizecolor 等,用于设置小部件中文本的字体和颜色;
  • 边距与填充marginpadding 等,用于设置小部件内容与其边框之间的空间。

2、设置Qt样式表

那想要实现圆形按键,就需要通过 Qt 样式表来对 QPushButton 对象进行设置,重点是 border-radius,这个关键属性,它决定了边框的圆角程度。

python 复制代码
        # 设置形状为圆形 初始样式表,使用f-string来插入直径的一半作为border-radius
        self.setStyleSheet(f"""
            QPushButton {{
                border-radius: {self.diameter // 2}px;
                padding: 0;
            }}
        """)

3、tQCircularButton类

那基于以上介绍,就可以得到自定义的圆形按键指示灯

python 复制代码
from tModels.tResource import *
import qdarkstyle
from qdarkstyle.dark.palette import DarkPalette  # noqa: E402
from qdarkstyle.light.palette import LightPalette  # noqa: E402


# 自定义圆形按钮指示灯,可以设置颜色;
class ctQCircularButton(QPushButton):
    # 构造函数
    def __init__(self, diameter=50, background_color="#8191B6", parent=None):
        super().__init__(parent)
        self.diameter = diameter
        self.background_color = background_color
        # 设置按钮的固定大小
        self.setFixedSize(self.diameter, self.diameter)
        # 设置按钮样式为圆形和深色模式
        self.f_recoverFunc()

    # 指示按键设置颜色函数
    def f_setColorFunc(self, is_active):
        """
        function:  指示按键设置颜色函数
              in:  is_active: 布尔值,True为绿色,False为红色
             out:  None
          return:  None
          others:  CircularButton Set Color Func
        """
        color = "#00FF7F" if is_active else 'red'
        # 更新样式表,使用f-string来插入新的颜色
        self.setStyleSheet(f"""  
            QPushButton {{  
                border: 2px solid {color};  
                border-radius: {self.diameter // 2}px;  
                color: black;  
                background-color: {color};  
                padding: 0;  
            }}  
        """)

    # 设置按钮样式为圆形和深色模式
    def f_recoverFunc(self):
        """
        function:  设置按钮样式为圆形和深色模式
              in:  None
             out:  None
          return:  None
          others:  Set Button Style Func
        """
        # 指示按键设置深色主题
        self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyside6', palette=DarkPalette))
        # 设置形状为圆形 初始样式表,使用f-string来插入直径的一半作为border-radius
        self.setStyleSheet(f"""
            QPushButton {{
                border-radius: {self.diameter // 2}px;
                padding: 0;
            }}
        """)

在以上代码中,引入了 qdarkstyle 的深色主题。

4、使用示例

python 复制代码
from PySide6.QtWidgets import QPushButton, QApplication, QWidget, QVBoxLayout
import qdarkstyle
from qdarkstyle.dark.palette import DarkPalette  # noqa: E402
from qdarkstyle.light.palette import LightPalette  # noqa: E402


class ctQCircularButton(QPushButton):
    # 构造函数
    def __init__(self, diameter=50, background_color="#8191B6", parent=None):
        super().__init__(parent)
        self.diameter = diameter
        self.background_color = background_color
        # 设置按钮的固定大小
        self.setFixedSize(self.diameter, self.diameter)
        # 设置按钮样式为圆形和深色模式
        self.f_recoverFunc()

    # 指示按键设置颜色函数
    def f_setColorFunc(self, is_active):
        """
        function:  指示按键设置颜色函数
              in:  is_active: 布尔值,True为绿色,False为红色
             out:  None
          return:  None
          others:  CircularButton Set Color Func
        """
        color = "#00FF7F" if is_active else 'red'
        # 更新样式表,使用f-string来插入新的颜色
        self.setStyleSheet(f"""  
            QPushButton {{  
                border: 2px solid {color};  
                border-radius: {self.diameter // 2}px;  
                color: black;  
                background-color: {color};  
                padding: 0;  
            }}  
        """)

    # 设置按钮样式为圆形和深色模式
    def f_recoverFunc(self):
        """
        function:  设置按钮样式为圆形和深色模式
              in:  None
             out:  None
          return:  None
          others:  Set Button Style Func
        """
        # 指示按键设置深色主题
        self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyside6', palette=DarkPalette))
        # 设置形状为圆形 初始样式表,使用f-string来插入直径的一半作为border-radius
        self.setStyleSheet(f"""
            QPushButton {{
                border-radius: {self.diameter // 2}px;
                padding: 0;
            }}
        """)


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyside6', palette=DarkPalette))
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        # 创建圆形按钮
        btn = ctQCircularButton(50)
        layout.addWidget(btn)

        # 示例:改变颜色
        btn.f_setColorFunc(True)  # 变为绿色
        # btn.f_setColorFunc(False)  # 变为红色,取消上面这行的注释来查看效果

        self.setLayout(layout)
        self.setWindowTitle('圆形按钮示例')
        self.setGeometry(100, 100, 200, 150)


if __name__ == '__main__':
    app = QApplication([])
    ex = MainWindow()
    ex.show()
    app.exec()
    

也可以根据自己的需要进行其他设置,如边框的颜色、边框的粗细等。

相关推荐
维度攻城狮2 小时前
实现在Unity3D中仿真汽车,而且还能使用ros2控制
python·unity·docker·汽车·ros2·rviz2
简简单单做算法2 小时前
基于mediapipe深度学习和限定半径最近邻分类树算法的人体摔倒检测系统python源码
人工智能·python·深度学习·算法·分类·mediapipe·限定半径最近邻分类树
hvinsion3 小时前
基于PyQt5的自动化任务管理软件:高效、智能的任务调度与执行管理
开发语言·python·自动化·自动化任务管理
飞飞翼5 小时前
python-flask
后端·python·flask
林九生6 小时前
【Python】Browser-Use:让 AI 替你掌控浏览器,开启智能自动化新时代!
人工智能·python·自动化
猿界零零七6 小时前
执行paddle.to_tensor得到全为0
python·paddle
青花瓷7 小时前
智谱大模型(ChatGLM3)PyCharm的调试指南
人工智能·python·大模型·智谱大模型
独好紫罗兰7 小时前
洛谷题单2-P5715 【深基3.例8】三位数排序-python-流程图重构
开发语言·python·算法
mqiqe8 小时前
Spring MVC 页面跳转方案与区别
python·spring·mvc
小白的高手之路8 小时前
torch.nn.Conv2d介绍——Pytorch中的二维卷积层
人工智能·pytorch·python·深度学习·神经网络·机器学习·cnn