Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 308
alphanumeric Avatar asked Jul 09 '14 16:07

alphanumeric


2 Answers

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

like image 104
Trilarion Avatar answered Sep 18 '22 08:09

Trilarion


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

like image 36
Manjunatha S Kedilaya Avatar answered Sep 17 '22 08:09

Manjunatha S Kedilaya