Qt drawRect in background

筅森魡賤 提交于 2019-12-06 04:13:19

问题


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();
}

回答1:


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).



来源:https://stackoverflow.com/questions/7942996/qt-drawrect-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!