gct
gct

Reputation: 14583

Styling QPushButton with CSS?

I'm trying to create a QPushButton that's just got an icon and a constant background color. So that I can swap out the icon when the user clicks it, without any other apparent effects (this is for a roll-up/roll-down feature). I've added an entry like this to my stylesheet:

QPushButton.ToggleButton {
    background-color: #8af; 
}

and set the button's class to match, and this does indeed give me the look I want, except that when I click on it the background color changes to a lighter blue, which I don't want. What am I missing?

Edit: I guess I should mention I'm using Qt 4.5 and PyQt 4.6 to do this...

Upvotes: 1

Views: 9999

Answers (4)

Bleadof
Bleadof

Reputation: 1193

Answer

Try giving the button an ID with QObject::setObjectName and then applying the style with #idSelector?

In Python the code would probably look something like this:

button = QPushButton(self)
button.setObjectName("ToggleButton")

and stylesheet like this:

#ToggleButton:pressed {
  background-color: #8af;
}

Further reading

Upvotes: 1

yan bellavance
yan bellavance

Reputation: 4850

open the button's stylesheet in Qt designer and try this:
QPushButton:pressed { image: url(/path/to/your/file/fileName.png); }

Upvotes: 0

Caleb Huitt - cjhuitt
Caleb Huitt - cjhuitt

Reputation: 14941

I know people like using stylesheets, but in this situation I think it is just as easy to make a custom button. Define a class that inherits from QAbstractButton, and override the paint() method. In the paint method, fill the rect with your desired background color, and then paint the current icon on top. It might be slightly more complicated if you want the border around the button as well, but not a lot.

Alternately, you could also look at the roles for QPalette, specifically QPalette::Light and QPalette::Midlight, which might be used to adjust the color of the button when pressed.

Upvotes: 1

Jorge Israel Peña
Jorge Israel Peña

Reputation: 38626

I'm guessing doing background-color: #8af !important; would be too obvious so I'm assuming that doesn't work. It's worth a try if you haven't done it yet.

Otherwise, as noted in this question, there are specific states you can style. Try setting the same background color for the pressed state:

QPushButton.ToggleButton:pressed { background-color: #8af; }

Sorry if I misunderstood. Hope that helps.

Upvotes: 0

Related Questions