用PyQt闪烁窗口小部件

问题描述:

我只想让QDialog中的某些元素闪烁(改变背景颜色)。用PyQt闪烁窗口小部件

现在最好我想能够使用已经存在的东西并封装闪烁状态,即用css3闪烁或可能用QPropertyAnimation

因为我没有找到这个选项我试过不太最佳解决方案的任何好的信息:从对话框__init__

摘录:

self.timer = QTimer() 
self.timer.timeout.connect(self.update_blinking) 
self.timer.start(250) 
self.last_blinked = None 

def update_blinking(self): 
    self.frame.setStyleSheet(
     self.STYLE_BLINK_ON if self.blink else self.STYLE_BLINK_OFF) 
    self.blink = not self.blink 

其中STYLE_BLINK_ONSTYLE_BLINK_OFF是一些CSS指定背景颜色。 这一工程,但

  1. 我觉得超级难看,感觉就像代码90年代
  2. 作为频繁样式更新中断按钮,点击它是不可用的。

2的解释:假设应该闪烁的小部件是一个帧。 单击框架内的按钮时,如果在释放鼠标按钮之前发生框架的样式更新,则不会发出clicked信号。

封装事物并且不需要我手动启动计时器的完全不同的解决方案当然是首选。 但是,如果有人至少想出了解决点2的解决方案,我将不胜感激。

一种方法是使用QPropertyAnimationQPropertyAnimation interpolates over Qt properties - 这个事实会导致困难:

1)通过样式表更改外观 - 动画无法使用字符串,因为它们不是可插入的。

2)直接操作背景 - 背景颜色存储在QWidget.palette深处,它不是QProperty。可能的解决方法是把背景颜色成widget的属性:

class AnimatedWidget(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() 

    def getBackColor(self): 
     return self.palette().color(QtGui.QPalette.Background) 

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

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

另一种方法是处理QStateMachine秒。他们能够操纵任何属性,而不仅仅是可插入的属性:

class StateWidget(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() 
+0

这些选项看起来好多了!我知道我的问题并不在我的问题中,但我希望它,如果答案也提供了一种方法将动画应用于现有的Widget,使其可以打开/关闭 – IARI