1

How can I get the pressed background color of a QPushButton?

if (isDown())
    _BGColor = <pressed background color>; // how to get this???
else
    _BGColor = palette().color(QPalette::Background); // this is to get the idle backcolor

Thanks in advance!!!

Toots
  • 21
  • 3
  • 1
    Welcome to Stackoverflow. Could you explain what are you trying to do? It seems that getting of this color is not a good idea. May be we can find better solution of your initial problem? – Ilya Apr 08 '16 at 06:00
  • I have a QPushButton subclass, when the button is long pressed, I want to draw a circle with the inverse color of the background then inside it is a check symbol with the background color. Another option for me is to erase some portion of the circle (making that portion transparent) to create a check mark. – Toots Apr 08 '16 at 07:18
  • What I am trying to do is an overlay circle in my button with a check shaped whole in the middle of it. It's for the checked property of the button, like having a check box but I want to render it as drawing. – Toots Apr 08 '16 at 07:21
  • 1
    Did you written above code in PaintEvent of you sub class, Try to write it in PaintEvent and call Update function in mousePressEvent. This should give you current value for the Background Color. – Atul N Apr 08 '16 at 07:32
  • I have tried to use `update()` and/or `repaint()` above `setDown(true)` but it's not getting the current value for Background color. – Toots Apr 08 '16 at 07:48
  • Additional info, I'am using styleSheet for updating background color for press, hover, etc. – Toots Apr 08 '16 at 08:44

1 Answers1

1

It's very difficult (if not impossible) to find a way to get the backgound color of a button when it's pressed, because it depends on the style, and it's not guaranteed that the style respects the palette.

However I suggest two different approaches:

  1. You can set you own background color using style sheets (simpler) or implement the painting of the button yourself, using styles or reimplementing paintEvent(). See Customizing QPushButton

  2. To paint over the button with the inverse color, you can set a composition mode to the painter in order to get the inverse color.

For example:

painter.setPen(QColor(255, 255, 255));
painter.setCompositionMode(QPainter::RasterOp_SourceAndNotDestination);

(note that using this example, the inverse color of middle grey (128, 128, 128) is exactly the same color)

See QPainter::CompositionMode

Fabio
  • 2,522
  • 1
  • 15
  • 25