【发布时间】:2020-02-28 00:48:09
【问题描述】:
我已经在 PyQt5 中做了一个小项目,我想尝试使用样式表让它看起来更好一些。为了测试,我将an example from W3Schools 复制到一个新项目中,看看它是否可以工作。该示例是一个背景从白色渐变为绿色的按钮。一切正常,除了不会褪色,而是立即发生过渡。我的问题是如何获得淡化效果?我也很好奇如何在按钮的其他方面(例如大小或形状)获得相同的过渡效果。
我进行了很多搜索,但我发现的所有相关内容都超出了我的知识范围。我所知道的是,我可能不得不对其进行编码而不是使用样式表,但我不完全确定如何做到这一点。我在想我可以制作一个不断改变颜色的函数,但我也认为可能有更好的方法来做到这一点。
这是我转换 .ui 文件时生成的代码。
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(10, 10, 381, 281))
self.pushButton.setMouseTracking(False)
self.pushButton.setAutoFillBackground(False)
self.pushButton.setStyleSheet(".QPushButton{\n"
"background-color: #4CAF50;\n"
"border: none;\n"
"color: white;\n"
"padding: 16px 32px;\n"
"text-align: center;\n"
"text-decoration: none;\n"
"display: inline-block;\n"
"font-size: 16px;\n"
"margin: 4px 2px;\n"
"transition-duration: 0.4s;\n"
"cursor: pointer;\n"
"}\n"
"\n"
"#pushButton{\n"
"background-color: white;\n"
"color: black;\n"
"border: 2px solid #4CAF50;\n"
"}\n"
"\n"
"#pushButton:hover{\n"
"background-color: #4CAF50;\n"
"color: white;\n"
"}")
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.pushButton.setText(_translate("Dialog", "Click Here"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
这是样式表中的内容,但更具可读性。
.QPushButton{
background-color: #4CAF50;
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
}
#pushButton{
background-color: white;
color: black;
border: 2px solid #4CAF50;
}
#pushButton:hover{
background-color: #4CAF50;
color: white;
}
这是按钮的图片。
悬停之前
之后
【问题讨论】:
标签: python pyqt pyqt5 qtstylesheets