Sivam
Sivam

Reputation: 1129

Coloring QSlider for a particular range

I have a QSlider, with a range of 0 to 100,

What I need is to color the background of its groove from the range 20 to 80 only.

enter image description here

Upvotes: 2

Views: 3738

Answers (1)

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

I suggest you to subclass QSlider and reimplement paintEvent as the following:

void My_slider::paintEvent(QPaintEvent *ev) {
  QStyleOptionSlider opt;
  initStyleOption(&opt);

  opt.subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderHandle;
  if (tickPosition() != NoTicks) {
    opt.subControls |= QStyle::SC_SliderTickmarks;
  }

  QRect groove_rect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this);
  qDebug() << groove_rect;
  QSlider::paintEvent(ev);
  QRect rect(groove_rect.left() + 0.2 * groove_rect.width(), groove_rect.top(), 0.6 * groove_rect.width(), groove_rect.height());
  QPainter painter(this);
  painter.fillRect(rect, QBrush(Qt::red));
}

Upvotes: 5

Related Questions