4

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

1 回答 1

10

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

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

于 2011-10-30T03:48:51.493 回答