Qt绘制矩形在后台

Qt drawRect in background

本文关键字:后台 绘制 Qt      更新时间:2023-10-16

我想绘制一个滑块的背景。我试过这个,但是颜色覆盖了整个滑块。这是在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();
}

要设置小部件的背景,可以设置样式表:

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

下面的代码将设置小部件的背景,允许您做更多的事情:

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

,顺便说一句。下面两行示例代码将产生一个警告:

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

也就是使用GCC的这个:

QPainter::begin:一个油漆装置只能由一个画家在一段时间。

所以要确保,就像我在例子中做的那样,你要么做QPainter painter(this)要么做painter.begin(this)