12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- #!/usr/bin/env python
- # -*- encoding: utf-8 -*-
- '''
- @文件 :switch_button.py
- @时间 :2022/01/22 10:05:50
- @作者 :None
- @版本 :1.0
- @说明 :连接开关
- '''
- from utils.qt import QWidget, Signal, Qt, QRect, QPainter, QFont, QColor, QBrush, QPen
- from utils.globalvar import SD
- class SwitchButton(QWidget):
- """自定义Switch按钮"""
- # 信号
- checkedChanged = Signal(bool)
- def __init__(self, parent=None):
- super(SwitchButton, self).__init__(parent)
- # 设置无边框和背景透明
- self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
- self.setAttribute(Qt.WA_TranslucentBackground)
- self.resize(70, 30)
- self.state = False # 按钮状态:True表示开,False表示关
- def mousePressEvent(self, event):
- """鼠标点击事件:用于切换按钮状态"""
- super(SwitchButton, self).mousePressEvent(event)
- # self.state = False if self.state else True
- self.state = not self.state
- # 发射信号
- self.checkedChanged.emit(self.state)
- self.update()
- def paintEvent(self, event):
- """绘制按钮"""
- super(SwitchButton, self).paintEvent(event)
- # 创建绘制器并设置抗锯齿和图片流畅转换
- painter = QPainter(self)
- painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
- # 定义字体样式
- font = QFont('Microsoft YaHei')
- font.setPixelSize(14)
- painter.setFont(font)
- # 开关为开的状态
- if self.state:
- painter.setPen(Qt.NoPen)
- brush = QBrush(QColor('#999999'))
- painter.setBrush(brush)
- painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)
- painter.setPen(Qt.NoPen)
- brush.setColor(QColor('#006400'))
- painter.setBrush(brush)
- painter.drawRoundedRect(43, 3, 24, 24, 12, 12)
- # 开关为关的状态
- else:
- painter.setPen(Qt.NoPen)
- brush = QBrush(QColor('#999999'))
- painter.setBrush(brush)
- painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)
- painter.setPen(Qt.NoPen)
- brush.setColor(QColor('#006400'))
- painter.setBrush(brush)
- painter.drawRoundedRect(3, 3, 24, 24, 12, 12)
|