switch_button.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @文件 :switch_button.py
  5. @时间 :2022/01/22 10:05:50
  6. @作者 :None
  7. @版本 :1.0
  8. @说明 :连接开关
  9. '''
  10. from utils.qt import QWidget, Signal, Qt, QRect, QPainter, QFont, QColor, QBrush, QPen
  11. from utils.globalvar import SD
  12. class SwitchButton(QWidget):
  13. """自定义Switch按钮"""
  14. # 信号
  15. checkedChanged = Signal(bool)
  16. def __init__(self, parent=None):
  17. super(SwitchButton, self).__init__(parent)
  18. # 设置无边框和背景透明
  19. self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
  20. self.setAttribute(Qt.WA_TranslucentBackground)
  21. self.resize(70, 30)
  22. self.state = False # 按钮状态:True表示开,False表示关
  23. def mousePressEvent(self, event):
  24. """鼠标点击事件:用于切换按钮状态"""
  25. super(SwitchButton, self).mousePressEvent(event)
  26. # self.state = False if self.state else True
  27. self.state = not self.state
  28. # 发射信号
  29. self.checkedChanged.emit(self.state)
  30. self.update()
  31. def paintEvent(self, event):
  32. """绘制按钮"""
  33. super(SwitchButton, self).paintEvent(event)
  34. # 创建绘制器并设置抗锯齿和图片流畅转换
  35. painter = QPainter(self)
  36. painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
  37. # 定义字体样式
  38. font = QFont('Microsoft YaHei')
  39. font.setPixelSize(14)
  40. painter.setFont(font)
  41. # 开关为开的状态
  42. if self.state:
  43. painter.setPen(Qt.NoPen)
  44. brush = QBrush(QColor('#999999'))
  45. painter.setBrush(brush)
  46. painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)
  47. painter.setPen(Qt.NoPen)
  48. brush.setColor(QColor('#006400'))
  49. painter.setBrush(brush)
  50. painter.drawRoundedRect(43, 3, 24, 24, 12, 12)
  51. # 开关为关的状态
  52. else:
  53. painter.setPen(Qt.NoPen)
  54. brush = QBrush(QColor('#999999'))
  55. painter.setBrush(brush)
  56. painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)
  57. painter.setPen(Qt.NoPen)
  58. brush.setColor(QColor('#006400'))
  59. painter.setBrush(brush)
  60. painter.drawRoundedRect(3, 3, 24, 24, 12, 12)