交易是这样的:当按下按钮 B 时,我试图让按钮 A“闪烁”,然后当用户按下按钮 A 时,闪烁应该停止。此外,按钮 A 应该回到原来的状态。
经过长时间阅读 SO 的文档和其他问题后,我现在有了以下代码:
蟒蛇 2.7
class Widget(QWidget):
def __init__(self):
super(Widget, self).__init__()
self.resize(300,200)
layout = QVBoxLayout(self)
self.button_stop = QPushButton("Stop")
layout.addWidget(self.button_stop)
self.button_start = QPushButton("Start", self)
layout.addWidget(self.button_start)
self.animation = QPropertyAnimation(self, "color", self)
self.animation.setDuration(1000)
self.animation.setLoopCount(100)
self.animation.setStartValue(self.color)
self.animation.setEndValue(self.color)
self.animation.setKeyValueAt(0.1, QColor(0,255,0))
self.button_start.clicked.connect(self.animation.start)
self.button_stop.clicked.connect(lambda: self.stop())
def stop(self):
self.animation.stop()
self.button_stop.setStyleSheet("")
def getColor(self):
return self.button_stop.palette().base()
def setColor(self, color):
palette = self.button_stop.palette()
palette.setColor(self.button_stop.backgroundRole(), color)
self.button_stop.setAutoFillBackground(True)
self.button_stop.setPalette(palette)
color = pyqtProperty(QColor, getColor, setColor)
if __name__ == "__main__":
app = QApplication([])
w = Widget()
w.show()
app.exec_()
我在这个问题中主要从@Alexander Lutsenko 获得的代码本身,在这里和那里进行了一些修改以测试我的需求。主要部分很简单:我创建了一个带有两个的窗口QPushButton
,一个用于启动,QPropertyAnimation
另一个用于停止它。它QPropertyAnimation
本身应用于其中一个按钮。理论上它应该改变按钮的背景颜色,但由于这个其他问题中解释的限制,它只为QPushButton
. 我对此很好,它看起来并不那么令人讨厌。
问题
开始动画后,如果我按下Stop
按钮,按钮不会回到原来的状态(没有彩色边框),而是保持Stop
按下按钮时的动画颜色。
此外,我收到以下警告:
TypeError: unable to convert a Python 'QBrush' object to a C++ 'QColor' instance
但是脚本继续运行,动画继续运行,所以这不会破坏任何东西。
问题
如何正确“重置”按钮的样式表?是否有另一种(可能更好和 pythonic)方法来做闪烁的按钮?非常感谢!