首页 > 解决方案 > 如何在悬停时为 qpushbutton 背景的渐变设置从左到右的动画?

问题描述

我正在练习我的编程技能,并且正在尝试使用PyQt. 我是在Login V4之后设计的。现在,当您将鼠标悬停在登录按钮上时,我正在尝试从登录按钮实现酷炫的渐变动画。但是为CSS类似的东西设置动画的代码在qt stylesheet. 我用 Qt Designer 设计了这个应用程序。甚至可以在 中创建该动画pyqt吗?如果是,你是怎么做到的?

我的应用程序如下所示:

在此处输入图像描述

登录按钮的样式表代码:

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;
}

标签: pythonpyqtpyqt5gradientqtstylesheets

解决方案


正如您所怀疑的,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_())

推荐阅读