16

I am trying to find out the background color of a QWidget or QGLWidget so that I can use it with qglClearColor() to make the OpenGL part appear natively within the widget (without for example a black background).

I figured I could fetch backgroundRole() of my widget but I am having problems converting it to a QColor. There is QPalette::color(QColorRole) but it isn't static and I have no idea how I would have to create an instance of QPalette to do the transformation.

Nils Werner
  • 34,832
  • 7
  • 76
  • 98
  • 1
    Did you try calling `qApp->palette()` to obtain application-wide palette and then call `QPalette::brush()` or `QPalette::color()`? – user2155932 Mar 20 '13 at 09:40

1 Answers1

33

Use QWidget::palette().color(QWidget::backgroundRole())to receive the color of the background color role for that widget. Obviously, this should also work with any class that inherits QWidget.

Sir Digby Chicken Caesar
  • 3,063
  • 1
  • 23
  • 31
  • Your call to `qglClearColor` is NOT in your QGLWidget subclass's constructor right? It should be in intializeGL, paintGL, or any otherone of the functions that can only be called AFTER your OpenGL context is established. – Sir Digby Chicken Caesar Mar 20 '13 at 09:59
  • Yes, it is in initializeGL. I forgot to add `glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);` to `paintG()`. – Nils Werner Mar 20 '13 at 10:01
  • Hm... I am trying this with a control that inherits `QPlainTextEdit` and it doesn't seem to work (`auto cr = pte->backgroundRole(); QPalette p = pte->palette(); QColor col = p.color(cr);`). I don't know if I am missing sth. I have found some code for setting its background that is totally different but working (at least on Windows that I tested it): http://stackoverflow.com/a/1532179/964053. I have tried getting the color like so: `ui->plainTextEdit->palette().base().color()`, but it's my impression that this doesn't work all of the times. So, confusing the whole Qt palette class... – NoOne Aug 28 '15 at 20:29