1 回答
TA贡献1883条经验 获得超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_())
添加回答
举报