How to change QPushButton text and background color

落花浮王杯 提交于 2019-11-30 00:47:24

问题


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

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 QPushButton display by giving it a text and background color. The following line of code (which is supposed to change background color) has no effect on QPushButton connected to QMenu.

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

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


回答1:


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

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

Example (using 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:




回答2:


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



来源:https://stackoverflow.com/questions/24659239/how-to-change-qpushbutton-text-and-background-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!