Skip to content Skip to sidebar Skip to footer

Blinking Widget With Pyqt

I simply want some elements inside a QDialog to be blinking (altering background color). Now preferably I'd like to be able to use something that already exists and encapsulates th

Solution 1:

The one way is to use QPropertyAnimation. QPropertyAnimation interpolates over Qt properties - this fact causes difficulties:

1) Change appearance via style sheet -- animation cannot work with strings, because they're not interpolable.

2) Manipulate background directly -- background color is stored deep inside QWidget.palette, it's not a QProperty. The possible solution is to transform background color into a widget's property:

classAnimatedWidget(QtGui.QWidget):
    def__init__(self):
        QtGui.QWidget.__init__(self)

        color1 = QtGui.QColor(255, 0, 0)
        color2 = QtGui.QColor(0, 255, 0)

        self.color_anim = QtCore.QPropertyAnimation(self, 'backColor')
        self.color_anim.setStartValue(color1)
        self.color_anim.setKeyValueAt(0.5, color2)
        self.color_anim.setEndValue(color1)
        self.color_anim.setDuration(1000)
        self.color_anim.setLoopCount(-1)
        self.color_anim.start()

    defgetBackColor(self):
        return self.palette().color(QtGui.QPalette.Background)

    defsetBackColor(self, color):
        pal = self.palette()
        pal.setColor(QtGui.QPalette.Background, color)
        self.setPalette(pal)

    backColor = QtCore.pyqtProperty(QtGui.QColor, getBackColor, setBackColor)

The other approach is dealing with QStateMachines. They're able to manipulate any properties, not only interpolable ones:

classStateWidget(QtGui.QWidget):
    def__init__(self):
        QtGui.QWidget.__init__(self)

        style1 = "background-color: yellow"
        style2 = "background-color: black"# animation doesn't work for strings but provides an appropriate delay
        animation = QtCore.QPropertyAnimation(self, 'styleSheet')
        animation.setDuration(150)

        state1 = QtCore.QState()
        state2 = QtCore.QState()
        state1.assignProperty(self, 'styleSheet', style1)
        state2.assignProperty(self, 'styleSheet', style2)
        #              change a state after an animation has played#                               v
        state1.addTransition(state1.propertiesAssigned, state2)
        state2.addTransition(state2.propertiesAssigned, state1)

        self.machine = QtCore.QStateMachine()
        self.machine.addDefaultAnimation(animation)
        self.machine.addState(state1)
        self.machine.addState(state2)
        self.machine.setInitialState(state1)
        self.machine.start()

Post a Comment for "Blinking Widget With Pyqt"