如何为 QPushButton 的背景颜色设置动画(动态更改按钮颜色)

时间:2021-02-21 09:04:04

标签: python animation pyqt5 qpropertyanimation

我正在尝试在 pyqt5 Python 中制作一个按钮,将背景颜色 - 阴影等从浅绿色更改为绿色,然后更改为深绿色。

我尝试了一些代码,但没有。

这是我的代码:

width: "80%",
height: "100%",
overflow: "auto",

我想让 eventFilter 开始动画,动画会是按钮的颜色变化。

1 个答案:

答案 0 :(得分:1)

按钮(和其他小部件)没有名为 color 的 qproperty,因此您不应该使用 QPropertyAnimation,在这种情况下,您应该使用 Qt StyleSheet 来更改颜色,因此您应该使用 QVariantAnimation:

import functools
from PyQt5 import QtCore, QtGui, QtWidgets


def helper_function(widget, color):
    widget.setStyleSheet("background-color: {}".format(color.name()))


def apply_color_animation(widget, start_color, end_color, duration=1000):
    anim = QtCore.QVariantAnimation(
        widget,
        duration=duration,
        startValue=start_color,
        endValue=end_color,
        loopCount=2,
    )
    anim.valueChanged.connect(functools.partial(helper_function, widget))
    anim.start(QtCore.QAbstractAnimation.DeleteWhenStopped)


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.button = QtWidgets.QPushButton()

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.button)

        timer = QtCore.QTimer(self, interval=5 * 1000)
        timer.timeout.connect(self.handle_timeout)
        timer.start()
        self.handle_timeout()

    def handle_timeout(self):
        apply_color_animation(
            self.button,
            QtGui.QColor("lightgreen"),
            QtGui.QColor("darkgreen"),
            duration=2500,
        )


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    w = Widget()
    w.show()
    sys.exit(app.exec_())