Source code for taurus.qt.qtgui.display.qled

#!/usr/bin/env python

# ###########################################################################
#
# This file is part of Taurus
#
# http://taurus-scada.org
#
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
#
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Taurus is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Taurus.  If not, see <http://www.gnu.org/licenses/>.
#
# ###########################################################################

"""A pure Qt led widget"""

__docformat__ = "restructuredtext"

import sys

from taurus.core.util.enumeration import Enumeration
from taurus.external.qt import Qt
from taurus.qt.qtgui.display.qpixmapwidget import QPixmapWidget
from taurus.qt.qtgui.icon import getCachedPixmap

LedStatus = Enumeration("LedStatus", ["ON", "OFF"])
LedSize = Enumeration("LedSize", [("SMALL", 24), ("LARGE", 48)])

PixmapLedColors = Enumeration(
    "LedColor",
    [
        "BLUE",
        "GREEN",
        "RED",
        "YELLOW",
        "ORANGE",
        "MAGENTA",
        "GRENOBLE",
        "BLACK",
        "WHITE",
    ],
)


[docs] def strToQColor(color_string): # To improve default Qt.QColor by name mapping = { "BLUE": Qt.QColor(0, 0, 255), "GREEN": Qt.QColor(0, 255, 0), "RED": Qt.QColor(255, 0, 0), "YELLOW": Qt.QColor(255, 255, 0), "ORANGE": Qt.QColor(255, 165, 0), "MAGENTA": Qt.QColor(255, 0, 255), "GRENOBLE": Qt.QColor("#7e6e2e"), "BLACK": Qt.QColor(50, 50, 50), "WHITE": Qt.QColor(255, 255, 255), } return mapping.get(color_string.upper(), Qt.QColor(str(color_string)))
class _BaseLedMixin(object): DefaultLedColor = "green" DefaultLedQColor = strToQColor(DefaultLedColor) DefaultLedStatus = True DefaultLedInverted = False DefaultBlinkingInterval = 0 def __init__(self, *args, **kwargs): self._ledStatus = self.DefaultLedStatus self._ledColor = self.DefaultLedColor self._ledInverted = self.DefaultLedInverted self._timer = None def getLedStatus(self): """Returns the led status :return: led status :rtype: bool """ return self._ledStatus def setLedStatus(self, status): """Sets the led status :param status: the new status :type status: bool """ self._ledStatus = bool(status) self._updateLed() def resetLedStatus(self): """Resets the led status""" self.setLedStatus(self.DefaultLedStatus) def toggleLedStatus(self): """toggles the current status of the led""" self.setLedStatus(not self.getLedStatus()) def getLedInverted(self): """Returns if the led is inverted. :return: inverted mode :rtype: bool """ return self._ledInverted def setLedInverted(self, inverted): self._ledInverted = bool(inverted) self._updateLed() def resetLedInverted(self): """Resets the led inverted mode""" self.setLedInverted(self.DefaultLedInverted) def getLedColor(self): """Returns the led color :return: led color :rtype: str """ return self._ledColor def setLedColor(self, color: str): """Sets the led color :param status: the new color :type status: str """ raise NotImplementedError def resetLedColor(self): """Resets the led color""" self.setLedColor(self.DefaultLedColor) def setBlinkingInterval(self, interval): """sets the blinking interval (the time between status switching). Set to a nonpositive number for disabling blinking :param interval: the blinking interval in millisecs. Set to 0 for disabling blinking :type interval: int """ if interval > 0: if self._timer is None: self._timer = Qt.QTimer(self) self._timer.timeout.connect(self.toggleLedStatus) self._timer.start(interval) else: if self._timer is not None: self._timer.stop() self._timer = None def getBlinkingInterval(self): """returns the blinking interval :return: blinking interval or 0 if blinking is not enabled. :rtype: int """ return 0 if self._timer is None else self._timer.interval() def resetBlinkingInterval(self): """resets the blinking interval""" self.setBlinkingInterval(self.__class__.DefaultBlinkingInterval) def minimumSizeHint(self): """Overwrite the default minimum size hint (0,0) to be (8,8) :return: the minimum size hint 8,8 :rtype: PyQt5.Qt.QSize """ return Qt.QSize(8, 8) def _updateLed(self): raise NotImplementedError #: This property holds the led status: False means OFF, True means ON #: #: **Access functions:** #: #: * :meth:`QLed.getLedStatus` #: * :meth:`QLed.setLedStatus` #: * :meth:`QLed.resetLedStatus` ledStatus = Qt.pyqtProperty( "bool", getLedStatus, setLedStatus, resetLedStatus, doc="led status" ) #: This property holds the led inverted: False means do not invert the #: status, True means invert the status #: #: **Access functions:** #: #: * :meth:`QLed.getLedInverted` #: * :meth:`QLed.setLedInverted` #: * :meth:`QLed.resetLedInverted` ledInverted = Qt.pyqtProperty( "bool", getLedInverted, setLedInverted, resetLedInverted, doc="led inverted mode", ) #: This property holds the blinking interval in millisecs. #: 0 means no blinking #: #: **Access functions:** #: #: * :meth:`QLed.getBlinkingInterval` #: * :meth:`QLed.setBlinkingInterval` #: * :meth:`QLed.resetBlinkingInterval` blinkingInterval = Qt.pyqtProperty( "int", getBlinkingInterval, setBlinkingInterval, resetBlinkingInterval, doc="blinking interval", )
[docs] class QLed(QPixmapWidget, _BaseLedMixin): """A Led drawn with png files""" DefaultLedPattern = "leds_images256:led_{color}_{status}.png" def __init__(self, parent=None, designMode=False): QPixmapWidget.__init__(self, parent) _BaseLedMixin.__init__(self) self._ledPatternName = self.DefaultLedPattern self._ledName = self.toLedName() self._updateLed()
[docs] def sizeHint(self): if self.layout() is None: return Qt.QSize(24, 24) return QPixmapWidget.sizeHint(self)
[docs] def isLedColorValid(self, name): """Determines if the given color name is valid. :param color: the color :type color: str :return: True is the given color name is valid or False otherwise :rtype: bool """ return name.upper() in PixmapLedColors
[docs] @Qt.pyqtSlot(str) def setLedColor(self, color: str): """Sets the led color :param status: the new color :type status: str """ color = str(color).lower() if not self.isLedColorValid(color): raise ValueError("Invalid color '%s'" % color) self._ledColor = color self._updateLed()
#: This property holds the led color #: #: **Access functions:** #: #: * :meth:`QLed.getLedColor` #: * :meth:`QLed.setLedColor` #: * :meth:`QLed.resetLedColor` ledColor = Qt.pyqtProperty( "QString", _BaseLedMixin.getLedColor, setLedColor, _BaseLedMixin.resetLedColor, doc="led color", )
[docs] def toLedName(self, status=None, color=None, inverted=None): """Gives the led name for the given status and color. If status or color are not given, the current led status or color are used. :param status: the status :type status: bool :param color: the color :type color: str :return: string containing the led name :rtype: str """ if status is None: status = self._ledStatus if color is None: color = self._ledColor if inverted is None: inverted = self._ledInverted if inverted: status = not status status = status and "on" or "off" return self._ledPatternName.format(color=color, status=status)
def _updateLed(self): self._ledName = self.toLedName() pixmap = getCachedPixmap(self._ledName) self.setPixmap(pixmap) return self.update()
[docs] @classmethod def getQtDesignerPluginInfo(cls): return { "module": "taurus.qt.qtgui.display", "group": "Taurus Display", "icon": "designer:ledred.png", "container": False, }
# -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ # QT property definition # -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
[docs] def getLedPatternName(self): """Returns the current led pattern name :return: led pattern name :rtype: str """ return self._ledPatternName
[docs] def setLedPatternName(self, name): """Sets the led pattern name. Should be a string containing a path to valid images. The string can contain the keywords: 1. {status} - transformed to 'on' of 'off' according to the status 2. {color} - transformed to the current led color Example: **:leds/images256/led_{color}_{status}.png** will be transformed to **:leds/images256/led_red_on.png** when the led status is True and the led color is red. :param name: new pattern :type name: str """ self._ledPatternName = str(name) self._updateLed()
[docs] def resetLedPatternName(self): """Resets the led pattern to `leds/images256/led_{color}_{status}.png` """ self.setLedPatternName(self.DefaultLedPattern)
#: This property holds the led pattern name #: #: **Access functions:** #: #: * :meth:`QLed.getLedPatternName` #: * :meth:`QLed.setLedPatternName` #: * :meth:`QLed.resetLedPatternName` ledPattern = Qt.pyqtProperty( "QString", getLedPatternName, setLedPatternName, resetLedPatternName, doc="led pattern name", )
[docs] class QLedPainted(Qt.QWidget, _BaseLedMixin): """A Led painted with QPainter""" def __init__(self, parent=None, designMode=False): """ Initializes a new instance of the QLedPainted class. """ Qt.QWidget.__init__(self, parent) _BaseLedMixin.__init__(self) self._ledColor = self.DefaultLedQColor self._timer = None self.resize(self.sizeHint()) self._updateLed()
[docs] def sizeHint(self): return Qt.QSize(25, 25)
[docs] @Qt.pyqtSlot("QVariant") def setLedColor(self, color): if isinstance(color, Qt.QColor): self._ledColor = color else: self._ledColor = strToQColor(color) self._updateLed()
[docs] def getLedColor(self): return self._ledColor
#: This property holds the led color #: #: **Access functions:** #: #: * :meth:`QLed.getLedColor` #: * :meth:`QLed.setLedColor` #: * :meth:`QLed.resetLedColor` ledColor = Qt.pyqtProperty( "QVariant", _BaseLedMixin.getLedColor, setLedColor, _BaseLedMixin.resetLedColor, doc="led color", )
[docs] @classmethod def getQtDesignerPluginInfo(cls): return { "module": "taurus.qt.qtgui.display", "group": "Taurus Display", "icon": "designer:ledred.png", "container": False, }
def _updateLed(self): self.update()
[docs] def paintEvent(self, event): with Qt.QPainter(self) as painter: painter.setRenderHint(Qt.QPainter.Antialiasing, True) # Resolve effective state (ON/OFF) considering inversion effective_on = self._ledStatus if self._ledInverted: effective_on = not effective_on # Base LED color (darken when OFF) fill_color = self.getLedColor() if not effective_on: fill_color = fill_color.darker(220) # Geometry: rim rect (outer) and body rect (inner) w, h = self.width(), self.height() min_side = min(w, h) size_factor = 0.06 # 6% of min_side # outer margin to avoid clipping, proportional to size margin = int(min_side * size_factor) # # clamp to reasonable range margin = min(margin, 3) # rim width also proportional to size rim_width = max(1, int(min_side * size_factor)) diam = min_side - 2 * margin x0 = (w - diam) / 2.0 y0 = (h - diam) / 2.0 rim_rect = Qt.QRectF(x0, y0, diam, diam) body_rect = rim_rect.adjusted(rim_width, rim_width, -rim_width, -rim_width) # Precompute body center/radius (used by multiple gradients) body_radius = body_rect.width() / 2.0 cx, cy = body_rect.center().x(), body_rect.center().y() painter.setPen(Qt.Qt.NoPen) # Drop shadow (painted manually for performance/control) shadow_offset = body_radius * 0.06 shadow_alpha = 180 shadow_rect = rim_rect.translated(shadow_offset, shadow_offset) shadow_grad = Qt.QRadialGradient( shadow_rect.center().x(), shadow_rect.center().y(), shadow_rect.width() / 2.0, ) shadow_grad.setColorAt(0.90, Qt.QColor(0, 0, 0, shadow_alpha)) shadow_grad.setColorAt(1.00, Qt.QColor(0, 0, 0, 0)) painter.setBrush(Qt.QBrush(shadow_grad)) painter.drawEllipse(shadow_rect) # Rim (fake stroke): dark ring with a subtle highlight rcx, rcy = rim_rect.center().x(), rim_rect.center().y() rr = rim_rect.width() / 2.0 rim_grad = Qt.QRadialGradient( rcx, rcy, rr, rcx - rr * 0.30, # focal point: shifts highlight to upper-left rcy - rr * 0.90, ) rim_grad.setColorAt(0.0, Qt.QColor(150, 150, 150, 255)) rim_grad.setColorAt(0.6, Qt.QColor(80, 80, 80, 255)) rim_grad.setColorAt(1.0, Qt.QColor(0, 0, 0, 255)) painter.setBrush(Qt.QBrush(rim_grad)) painter.drawEllipse(rim_rect) # LED body: main radial gradient (3D / glass feel) body_grad = Qt.QRadialGradient( cx, cy, body_radius, cx - body_radius * 0.30, # focal point: where light appears strongest cy - body_radius * 0.80, ) body_grad.setColorAt(0.0, fill_color.lighter(250)) # hot spot body_grad.setColorAt(0.4, fill_color) # mid tone body_grad.setColorAt(1.0, fill_color.darker(200)) # edge darkening painter.setBrush(Qt.QBrush(body_grad)) painter.drawEllipse(body_rect) # Secondary highlights (gloss/reflections) # Small helper to paint a radial "gloss" spot def _paint_gloss( center_x, center_y, gloss_radius, alpha0, alpha1, target_rect, mid_stop=0.6, ): g = Qt.QRadialGradient(center_x, center_y, gloss_radius) g.setColorAt(0.0, Qt.QColor(255, 255, 255, alpha0)) if mid_stop is not None: g.setColorAt(mid_stop, Qt.QColor(255, 255, 255, alpha1)) g.setColorAt(1.0, Qt.QColor(255, 255, 255, 0)) else: g.setColorAt(1.0, Qt.QColor(255, 255, 255, 0)) painter.setBrush(Qt.QBrush(g)) painter.setPen(Qt.Qt.NoPen) painter.drawEllipse(target_rect) if effective_on: # Top-left strong gloss affecting rim _paint_gloss( cx - body_radius * 0.40, cy - body_radius * 0.90, body_radius * 0.75, alpha0=180, alpha1=40, target_rect=rim_rect, mid_stop=0.6, ) # Subtle gloss spots around the body (very low alpha) _paint_gloss( cx - body_radius * 0.85, cy + body_radius * 0.35, body_radius * 0.80, alpha0=40, alpha1=0, target_rect=body_rect, mid_stop=None, ) _paint_gloss( cx + body_radius * 0.85, cy - body_radius * 0.15, body_radius * 0.80, alpha0=40, alpha1=0, target_rect=body_rect, mid_stop=None, ) _paint_gloss( cx + body_radius * 0.40, cy + body_radius * 0.90, body_radius * 0.80, alpha0=40, alpha1=0, target_rect=body_rect, mid_stop=None, )
def main(): """hello""" app = Qt.QApplication.instance() owns_app = app is None if owns_app: from taurus.qt.qtgui.application import TaurusApplication app = TaurusApplication(sys.argv, cmd_line_parser=None) w = Qt.QWidget() layout = Qt.QGridLayout() layout.setContentsMargins(2, 2, 2, 2) layout.setSpacing(2) w.setLayout(layout) for i, color in enumerate(PixmapLedColors.keys()): led = QLed() led.ledColor = color led.ledStatus = True layout.addWidget(led, i, 0) led = QLed() led.ledColor = color led.ledStatus = False layout.addWidget(led, i, 1) led = QLed() led.ledColor = color led.blinkingInterval = 500 layout.addWidget(led, i, 2) led = QLedPainted() led.ledColor = color led.ledStatus = True layout.addWidget(led, i, 3) led = QLedPainted() led.ledColor = color led.ledStatus = False layout.addWidget(led, i, 4) led = QLedPainted() led.ledColor = color led.blinkingInterval = 500 layout.addWidget(led, i, 5) class ColorChooser(Qt.QWidget): colorChoosed = Qt.Signal(Qt.QVariant) def __init__(self, parent=None): Qt.QWidget.__init__(self, parent) self.select_color_button = Qt.QPushButton("Select Free Color") mainLayout = Qt.QHBoxLayout() mainLayout.addWidget(self.select_color_button) self.select_color_button.clicked.connect(self.show_color_dialog) self.setLayout(mainLayout) # Slot function to show color dialog @Qt.pyqtSlot() def show_color_dialog(self): color = Qt.QColorDialog.getColor() self.select_color_button.setStyleSheet( f"QPushButton {{background-color: {color.name()};}}" ) self.colorChoosed.emit(Qt.QVariant(color)) w2 = Qt.QWidget() color_chooser = ColorChooser() pled = QLedPainted() l2 = Qt.QVBoxLayout() l2.addWidget(color_chooser) l2.addWidget(pled) w2.setLayout(l2) color_chooser.colorChoosed.connect(pled.setLedColor) mainW = Qt.QWidget() mainW.setLayout(Qt.QHBoxLayout()) mainW.layout().addWidget(w) mainW.layout().addWidget(w2) mainW.show() if owns_app: sys.exit(app.exec_()) else: return w if __name__ == "__main__": main()