Qt drawRect in background

Geore Shg picture Geore Shg · Oct 30, 2011 · Viewed 7.1k times · Source

I want to paint the background of a slider. I tried this but the color covers up the whole slider. This is in an inherited class of QSlider

void paintEvent(QPaintEvent *e) {
  QPainter painter(this);
  painter.begin(this);
  painter.setBrush(/*not important*/);

  // This covers up the control. How do I make it so the color is in
  // the background and the control is still visible?
  painter.drawRect(rect()); 

  painter.end();
}

Answer

Morten Kristensen picture Morten Kristensen · Oct 30, 2011

To set the background of a widget you could set the style sheet:

theSlider->setStyleSheet("QSlider { background-color: green; }");

The following will set the background of the widget, allowing you to do more:

void paintEvent(QPaintEvent *event) {
  QPainter painter;
  painter.begin(this);
  painter.fillRect(rect(), /* brush, brush style or color */);
  painter.end(); 

  // This is very important if you don't want to handle _every_ 
  // detail about painting this particular widget. Without this 
  // the control would just be red, if that was the brush used, 
  // for instance.
  QSlider::paintEvent(event);    
}

And btw. the following two lines of your sample code will yield a warning:

QPainter painter(this);
painter.begin(this);

Namely this one using GCC:

QPainter::begin: A paint device can only be painted by one painter at a time.

So make sure, as I do in my example, that you either do QPainter painter(this) or painter.begin(this).