温馨提示×

python qpushbutton的样式表如何应用

小樊
82
2024-09-06 15:37:27
栏目: 编程语言

在 PyQt5 中,要为 QPushButton 设置样式表,可以使用 setStyleSheet() 方法

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton

app = QApplication([])

window = QWidget()
layout = QVBoxLayout(window)

# 创建一个 QPushButton 实例
button = QPushButton("点击我")

# 设置按钮的样式表
button_stylesheet = '''
QPushButton {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

QPushButton:hover {
    background-color: #45a049;
}
'''

button.setStyleSheet(button_stylesheet)

layout.addWidget(button)
window.setLayout(layout)

window.show()
app.exec_()

在这个示例中,我们首先导入了所需的模块并创建了一个简单的窗口。然后,我们创建了一个 QPushButton 实例,并定义了一个名为 button_stylesheet 的字符串,其中包含了按钮的样式表。接下来,我们使用 setStyleSheet() 方法将样式表应用到按钮上。最后,我们将按钮添加到布局中并显示窗口。

在这个样式表中,我们设置了按钮的背景颜色、边框、文本颜色等属性。同时,我们还定义了按钮的悬停效果,当鼠标悬停在按钮上时,背景颜色会发生变化。

0