Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

python - How to change QPushButton text and background color

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...