led.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from PyQt5.QtGui import *
  2. from PyQt5.QtCore import *
  3. from PyQt5.QtWidgets import *
  4. allAttributes = ['colorOnBegin', 'colorOnEnd', 'colorOffBegin', 'colorOffEnd', 'colorBorderIn', 'colorBorderOut']
  5. allDefaultVal = [QColor(0, 180, 0), QColor(0, 150, 0), QColor(220, 0, 0), QColor(180, 0, 0), QColor(140, 140, 140),
  6. QColor(100, 100, 100)]
  7. allLabelNames = [u'灯亮圆心颜色:', u'灯亮边缘颜色:', u'灯灭圆心颜色:', u'灯灭边缘颜色:', u'边框内测颜色:',
  8. u'边框外侧颜色:',
  9. u'边框外侧半径:', u'边框内侧半径:', u'中间圆灯半径:']
  10. class Led(QAbstractButton):
  11. def __init__(self, parent=None):
  12. super(Led, self).__init__(parent)
  13. self.radiusBorderIn = None
  14. self.radiusCircle = None
  15. self.scaledSize = None
  16. self.radiusBorderOut = None
  17. self.colorOnEnd = None
  18. self.colorOnBegin = None
  19. self.colorBorderIn = None
  20. self.colorOffEnd = None
  21. self.colorOffBegin = None
  22. self.colorBorderOut = None
  23. self.initUI()
  24. def initUI(self):
  25. self.setMinimumSize(24, 24)
  26. self.setCheckable(True)
  27. self.scaledSize = 1000.0 # 为方便计算,将窗口短边值映射为1000
  28. self.setLedDefaultOption()
  29. self.radiusBorderOut = 500 # 边框外侧半径
  30. self.radiusBorderIn = 450 # 边框内侧半径
  31. self.radiusCircle = 400 # 中间圆灯半径
  32. # 将配置的颜色和属性对应
  33. def setLedDefaultOption(self):
  34. for attr, val in zip(allAttributes, allDefaultVal):
  35. setattr(self, attr, val)
  36. self.update()
  37. def resizeEvent(self, evt):
  38. self.update()
  39. def paintEvent(self, evt):
  40. painter = QPainter(self)
  41. painter.setRenderHint(QPainter.Antialiasing, True)
  42. painter.setPen(QPen(Qt.black, 1))
  43. realSize = min(self.width(), self.height()) # 窗口的短边
  44. painter.translate(self.width() / 2.0, self.height() / 2.0) # 原点平移到窗口中心
  45. painter.scale(realSize / self.scaledSize, realSize / self.scaledSize) # 缩放,窗口的短边值映射为self.scaledSize
  46. gradient = QRadialGradient(QPointF(0, 0), self.scaledSize / 2.0, QPointF(0, 0)) # 辐射渐变
  47. # 画边框外圈和内圈
  48. for color, radius in [(self.colorBorderOut, self.radiusBorderOut), # 边框外圈
  49. (self.colorBorderIn, self.radiusBorderIn)]: # 边框内圈
  50. gradient.setColorAt(1, color)
  51. painter.setBrush(QBrush(gradient))
  52. painter.drawEllipse(QPointF(0, 0), radius, radius)
  53. # 画内圆
  54. gradient.setColorAt(0, self.colorOnBegin if self.isChecked() else self.colorOffBegin)
  55. gradient.setColorAt(1, self.colorOnEnd if self.isChecked() else self.colorOffEnd)
  56. painter.setBrush(QBrush(gradient))
  57. painter.drawEllipse(QPointF(0, 0), self.radiusCircle, self.radiusCircle)