这里有一个交易:我试图让按钮A在按下按钮B时“闪烁”,当用户按下按钮A时,闪烁应该停止。此外,按钮A应该会回到原来的状态。在
在仔细阅读了SO的文档和其他问题之后,我现在有了以下代码:
Python2.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_()
代码本身我主要是从@alexanderlutsenko在this问题中得到的,在这里和那里做了一些修改来测试我的需求。主要部分很简单:我用两个QPushButton
创建一个窗口,一个用来启动QPropertyAnimation
,另一个用来停止它。QPropertyAnimation
本身应用于其中一个按钮。理论上它应该改变按钮的背景色,但是由于this other question中解释的限制,它只为QPushButton
提供了一个彩色的边框。我没意见,看起来没那么麻烦。在
问题
启动动画后,如果我按下Stop
按钮,按钮不会回到其原始状态(没有彩色边框),而是保持按下Stop
按钮时动画的颜色。在
此外,我得到以下警告:
TypeError: unable to convert a Python 'QBrush' object to a C++ 'QColor' instance
但是脚本一直在运行,动画也在继续,所以不会破坏任何东西。在
问题
如何正确地“重置”按钮的样式表?有没有其他的(也许更好的和Python式的)方法来做闪烁按钮的事情?谢谢!在
属性不会保存初始状态,因此即使对动画进行配对,也不会将其恢复到初始状态。因此,本例中的解决方案是将该状态保存在变量中,并创建一个
reset_color()
方法来再次恢复颜色。。在另一方面,错误消息:
TypeError: unable to convert to Python 'QBrush' object to a C ++ 'QColor' instance
表示代码self.button_stop.palette().base()
返回QBrush
,但它应该是QColor
,并且没有隐含的转换,因此必须更改实现。在按照顺序,我将创建一个继承自
QPushButton
的新类并实现这些属性。在相关问题 更多 >
编程相关推荐