如何为qpushbutton背景的渐变设置动画以使其在悬停时从左向右移动?

时间:2019-10-05 13:16:47

标签: python pyqt pyqt5 gradient qtstylesheets

我正在练习我的编程技能,并且尝试使用PyQt构建一个登录系统应用程序。我在Login V4之后进行了设计。现在,当您将鼠标悬停在“登录”按钮上时,我正在尝试实现该炫酷渐变动画。但是CSS中的动画代码qt stylesheet无效。我使用Qt Designer设计了该应用程序。甚至可以在pyqt中创建该动画吗?如果是,那你如何?

我的应用如下:

enter image description here

“登录”按钮的样式表代码:

QPushButton#login_button {
font: 75 10pt "Microsoft YaHei UI";
font-weight: bold;
color: rgb(255, 255, 255);
background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgb(61, 217, 245), stop:1 rgb(240, 53, 218));
border-style: solid;
border-radius:21px;
}

1 个答案:

答案 0 :(得分:3)

您怀疑Qt样式表不支持动画。在这种情况下,另一种方法是将QXAnimation用作QVariantAnimation:

from PyQt5 import QtCore, QtGui, QtWidgets


class LoginButton(QtWidgets.QPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setMinimumSize(60, 60)

        self.color1 = QtGui.QColor(240, 53, 218)
        self.color2 = QtGui.QColor(61, 217, 245)

        self._animation = QtCore.QVariantAnimation(
            self,
            valueChanged=self._animate,
            startValue=0.00001,
            endValue=0.9999,
            duration=250
        )

    def _animate(self, value):
        qss = """
            font: 75 10pt "Microsoft YaHei UI";
            font-weight: bold;
            color: rgb(255, 255, 255);
            border-style: solid;
            border-radius:21px;
        """
        grad = "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 {color1}, stop:{value} {color2}, stop: 1.0 {color1});".format(
            color1=self.color1.name(), color2=self.color2.name(), value=value
        )
        qss += grad
        self.setStyleSheet(qss)

    def enterEvent(self, event):
        self._animation.setDirection(QtCore.QAbstractAnimation.Forward)
        self._animation.start()
        super().enterEvent(event)

    def leaveEvent(self, event):
        self._animation.setDirection(QtCore.QAbstractAnimation.Backward)
        self._animation.start()
        super().enterEvent(event)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = QtWidgets.QWidget()
    lay = QtWidgets.QVBoxLayout(w)

    for i in range(5):
        button = LoginButton()
        button.setText("Login")
        lay.addWidget(button)
    lay.addStretch()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())