2

I am unsuccessfully trying to change the color of the handle on a QSlider. How do I change it to a custom color? I have subclassed QSlider so that I can reimplement the paint event and draw my own rectangle on it--now I want to set the color of the handle. In the creator of the subclassed widget, I did this:

setStyleSheet("handle:horizontal {color: red}");

I have tried all kinds of other properties besides color, including background-color, etc--nothing makes any change at all on the widget--it still stays the default grey. I'd swear my code wasn't executing at all, but I checked it in the debugger, and it is.

I tried moving the setStyleSheet into my paintEvent,; that made no difference. Here is the paintEvent--I don't know if it matters, but I suspect I'll get asked for it if I don't include it

void FilledSlider::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);
  QSlider::paintEvent(ev);
  int grooveCenter = groove_rect.bottom() - (groove_rect.bottom() - groove_rect.top())/2.0;
  QRect fillRectangle;
  int left;
  int width;
  if(direction < 0)
     {
        left = groove_rect.left() +  ((1.0 -filledPercentage) * groove_rect.width());
        width = filledPercentage * groove_rect.width();
     }
  else
     {
        left = groove_rect.left();
        width = groove_rect.width() * filledPercentage;
     }
  fillRectangle.setRect(left, grooveCenter, width, 0.2*groove_rect.height());
  QPainter painter(this);
  painter.fillRect(fillRectangle, QBrush(Qt::red));
}
jhowland
  • 365
  • 1
  • 5
  • 19
  • Where'd you learn how to write this paint event? Curious about the references you used. It might help me find you an answer. –  Jul 30 '16 at 19:01
  • 2
    Corresponding to [this](http://doc.qt.io/qt-4.8/stylesheet-examples.html#customizing-qslider) try `setStyleSheet("QSlider::handle:horizontal {background-color: red;}");`. If it doesn't work, try it with casual `QSlider`, not subclass. You could corrupt `paintEvent` or something else. – ilotXXI Jul 30 '16 at 20:02
  • I copied the paint event from here:http://stackoverflow.com/questions/17101378/coloring-qslider-for-particular-range – jhowland Jul 31 '16 at 22:21
  • I tried changing my object from my subclassed version to an ordinary QSlider--applied the style and it made no difference – jhowland Aug 01 '16 at 15:26

1 Answers1

3

Corresponding to this try setStyleSheet("QSlider::handle:horizontal {background-color: red;}");.

this was the answer, thank you iloXXI!

jhowland
  • 365
  • 1
  • 5
  • 19