python - 如何在悬停时为 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;
}
解决方案
正如您所怀疑的,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_())
推荐阅读
- c++ - 为什么返回一个在普通括号内用大括号初始化的向量会导致编译错误?
- python - 如何创建具有特定 python 版本的 jupyter notebook?
- html - 从 GO 模板获取原始源代码
- python - Python编程在休息后不会继续吗?
- java - 插入数据时出错 java.time.LocalDate 在 SpringBoot 中包含字段 dateOfBirth 类型 LocalDate
- python - 来自网站的响应不包含我试图使用 Xpath 和 Scrapy 找到的元素。但是使用 ChroPath 他们在那里
- sql - JSON自动的意外结果
- javascript - 我该如何控制标签来创建选择元素?
- browserstack - 无法在 BrowserStack 中使用麦克风
- blazor - 如何 blazor 注入 Globalization.CultureInfo("th-TH")