switch_button.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. class SwitchButton(QWidget):
  12. """自定义Switch按钮"""
  13. # 信号
  14. checkedChanged = Signal(bool)
  15. def __init__(self, parent=None):
  16. super(SwitchButton, self).__init__(parent)
  17. # 设置无边框和背景透明
  18. self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
  19. self.setAttribute(Qt.WA_TranslucentBackground)
  20. self.resize(70, 30)
  21. self.state = False # 按钮状态:True表示开,False表示关
  22. def mousePressEvent(self, event):
  23. """鼠标点击事件:用于切换按钮状态"""
  24. super(SwitchButton, self).mousePressEvent(event)
  25. # self.state = False if self.state else True
  26. self.state = not self.state
  27. # 发射信号
  28. self.checkedChanged.emit(self.state)
  29. self.update()
  30. def paintEvent(self, event):
  31. """绘制按钮"""
  32. super(SwitchButton, self).paintEvent(event)
  33. # 创建绘制器并设置抗锯齿和图片流畅转换
  34. painter = QPainter(self)
  35. painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
  36. # 定义字体样式
  37. font = QFont('Microsoft YaHei')
  38. font.setPixelSize(14)
  39. painter.setFont(font)
  40. # 开关为开的状态
  41. if self.state:
  42. # 绘制背景
  43. painter.setPen(Qt.NoPen)
  44. # brush = QBrush(QColor('#969696'))
  45. brush = QBrush(QColor('#006400'))
  46. painter.setBrush(brush)
  47. painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)
  48. # 绘制圆圈
  49. painter.setPen(Qt.NoPen)
  50. brush.setColor(QColor('#ffffff'))
  51. painter.setBrush(brush)
  52. painter.drawRoundedRect(43, 3, 24, 24, 12, 12)
  53. # 绘制文本
  54. painter.setPen(QPen(QColor('#ffffff')))
  55. painter.setBrush(Qt.NoBrush)
  56. painter.drawText(QRect(18, 4, 50, 20), Qt.AlignLeft, '开')
  57. # 开关为关的状态
  58. else:
  59. # 绘制背景
  60. painter.setPen(Qt.NoPen)
  61. brush = QBrush(QColor('#FFFFFF'))
  62. painter.setBrush(brush)
  63. painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)
  64. # 绘制圆圈
  65. pen = QPen(QColor('#999999'))
  66. pen.setWidth(1)
  67. painter.setPen(pen)
  68. painter.drawRoundedRect(3, 3, 24, 24, 12, 12)
  69. # 绘制文本
  70. painter.setBrush(Qt.NoBrush)
  71. painter.drawText(QRect(38, 4, 50, 20), Qt.AlignLeft, '关')