Skip to content Skip to sidebar Skip to footer

"blinking" Buttons In Pyqt5

Here's the deal: I'm trying to make button A 'blink' when button B is pushed, and the blinking should then stop when the user pushes button A. Furthermore, button A should then go

Solution 1:

The property does not save the initial state so even if you pair the animation it will not be restored to the initial state. So the solution in this case is to save that state in a variable and create a reset_color() method that restores the color again..

On the other hand the error message: TypeError: unable to convert to Python 'QBrush' object to a C ++ 'QColor' instance indicates that the code self.button_stop.palette().base() returns a QBrush, but it is expected a QColor, and there is no conversion implied, so that implementation must be changed.

As a matter of order I will create a new class that inherits from QPushButton and implement those properties.

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

classBlinkButton(QPushButton):
    def__init__(self, *args, **kwargs):
        QPushButton.__init__(self, *args, **kwargs)
        self.default_color = self.getColor()

    defgetColor(self):
        return self.palette().color(QPalette.Button)

    defsetColor(self, value):
        if value == self.getColor():
            return
        palette = self.palette()
        palette.setColor(self.backgroundRole(), value)
        self.setAutoFillBackground(True)
        self.setPalette(palette)

    defreset_color(self):
        self.setColor(self.default_color)

    color = pyqtProperty(QColor, getColor, setColor)


classWidget(QWidget):

    def__init__(self):
        super(Widget, self).__init__()

        self.resize(300,200)
        layout = QVBoxLayout(self)

        self.button_stop = BlinkButton("Stop")
        layout.addWidget(self.button_stop)

        self.button_start = QPushButton("Start", self)
        layout.addWidget(self.button_start)

        self.animation = QPropertyAnimation(self.button_stop, "color", self)
        self.animation.setDuration(1000)
        self.animation.setLoopCount(100)
        self.animation.setStartValue(self.button_stop.default_color)
        self.animation.setEndValue(self.button_stop.default_color)
        self.animation.setKeyValueAt(0.1, QColor(0,255,0))

        self.button_start.clicked.connect(self.animation.start)
        self.button_stop.clicked.connect(self.stop)

    defstop(self):
        self.animation.stop()
        self.button_stop.reset_color()

if __name__ == "__main__":
    app = QApplication([])
    w = Widget()
    w.show()
    app.exec_()

Post a Comment for ""blinking" Buttons In Pyqt5"