我想画一个滑块的背景。我尝试了这个,但颜色覆盖了整个滑块。这是一个继承的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();
}
答案 0 :(得分:9)
要设置小部件的背景,您可以设置样式表:
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)
。