Chris
Chris

Reputation: 639

Changing QPushButton Color when Pressed

Is there a way to change the background color of a QPushButton which is pressed by modifying its QPalette object? I realize it can be done with style sheets but would like a way to do it by modifying the QPalette. Something similar to how one changes the background color of the button when not pressed:

QPushButton myButton;
QPalette p(myButton.palette());

p.setColor(QPalette::Button, QColor("#ffffff"));
myButton.setPalette(p);

Upvotes: 1

Views: 27008

Answers (4)

Shinnok
Shinnok

Reputation: 6389

Connect to QPushButton's pressed() signal and update the palette with your desired color and then connect to released() signal and switch back the color to the old color. That should do it.

You may want to run update() after settings the colors or in extreme cases repaint().

Upvotes: 2

giuspen
giuspen

Reputation: 1401

Simply add a stylesheet to the qbushbutton itself or to his parent qwidget:

qwidget.setStyleSheet("QPushButton:checked { background-color: red; }")

This will set the background color to red when the QPushButton is checked.

Upvotes: 4

Naruto
Naruto

Reputation: 9634

you can set stylesheet for button when it is pressed.. here is the Example tells how to set style sheet for button.. but in your case u need to have two different style sheets, one is button pressed and similarly when it is released you should reset with some other stylesheet.

Upvotes: 1

Stephen Chu
Stephen Chu

Reputation: 12832

Connect to the button's pressed signal and set the palette in the connected slot. You may have to call repaint() to force an immediate update.

Upvotes: 1

Related Questions