Qt在后台绘制矩形

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

1
你想做的是给一个小部件涂上背景色吗?请再具体一些。 - Morten Kristensen
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)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接