Python 如何更改 QPushButton 文本和背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24659239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:57:55  来源:igfitidea点击:

How to change QPushButton text and background color

pythonqtpyqtqtstylesheets

提问by alphanumeric

I am using following code to connect QMenuto QPushButton. When button is clicked a pull-down menu with multiple sub-menu's items is shown.

我正在使用以下代码连接QMenuQPushButton. 单击按钮时,会显示包含多个子菜单项的下拉菜单。

button=QPushButton()
button.setText("Press Me")

font=QtGui.QFont()
button.setFont(font)
button.setSizePolicy(ToolButtonSizePolicy)

button.setPopupMode(QtGui.QToolButton.InstantPopup)
menu=QtGui.QMenu()
button.setMenu(menu)

menuItem1=menu.addAction('Menu Item1')
menuItem2=menu.addAction('Menu Item2') 

Now depending on a condition I would like to customize QPushButtondisplay by giving it a text and background color. The following line of code (which is supposed to change background color) has no effect on QPushButtonconnected to QMenu.

现在根据条件,我想QPushButton通过给它一个文本和背景颜色来自定义显示。以下代码行(应该更改背景颜色)对QPushButton连接到 QMenu没有影响。

button.setStyleSheet('QPushButton {background-color: #A3C1DA}')

I would like to know how to change the background color of QPushButtonas well as button's text's color.

我想知道如何更改QPushButton按钮文本颜色的背景颜色。

采纳答案by Trilarion

Apart from some inconsistencies with your code example setting the background color and text color of a QPushButtonworks just fine with:

除了与您的代码示例存在一些不一致之外,设置背景颜色和文本颜色的QPushButton工作效果很好:

setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')

Example (using PySide):

示例(使用 PySide):

from PySide import QtGui

app = QtGui.QApplication([])

button = QtGui.QPushButton()
button.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
button.setText('Press Me')
menu = QtGui.QMenu()
menuItem1 = menu.addAction('Menu Item1')
menuItem2 = menu.addAction('Menu Item2')

button.setMenu(menu)
button.show()

app.exec_()

results in:

结果是:

enter image description here

在此处输入图片说明

回答by Manjunatha S Kedilaya

For those who still want to change color of button with the instruction

对于那些仍然想按照说明更改按钮颜色的人

button.setStyleSheet('QPushButton {background-color: #A3C1DA}')

and not able to do so, just modify the above instruction to

并不能这样做,只需将上述说明修改为

button.setStyleSheet('QPushButton {background-color: #A3C1DA; border:  none}')

And it will change the button color, so the trick is to remove the border

它会改变按钮的颜色,所以诀窍是去除边框