【问题标题】:How do I change color of the handle on QSlider如何更改 QSlider 上手柄的颜色
【发布时间】:2016-12-04 16:05:51
【问题描述】:

我没有成功尝试更改 QSlider 上手柄的颜色。如何将其更改为自定义颜色?我将 QSlider 子类化,以便我可以重新实现绘制事件并在其上绘制我自己的矩形——现在我想设置手柄的颜色。在子类小部件的创建者中,我这样做了:

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

我已经尝试了除颜色之外的所有其他属性,包括背景颜色等——小部件上没有任何改变——它仍然保持默认的灰色。我发誓我的代码根本没有执行,但我在调试器中检查了它,它是。

我尝试将 setStyleSheet 移动到我的paintEvent 中;这没有什么区别。这是paintEvent——我不知道它是否重要,但我怀疑如果我不包含它,我会被要求提供它

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

【问题讨论】:

  • 您是从哪里学习到如何编写这个绘画事件的?对您使用的参考文献感到好奇。它可能会帮助我找到你的答案。
  • 对应this试试setStyleSheet("QSlider::handle:horizontal {background-color: red;}");。如果它不起作用,请尝试使用随便的QSlider,而不是子类。你可能会破坏paintEvent 或其他东西。
  • 我从这里复制了绘画事件:stackoverflow.com/questions/17101378/…
  • 我尝试将我的对象从我的子类版本更改为普通的 QSlider——应用了该样式,但没有任何区别

标签: qt qslider qstylesheet


【解决方案1】:

对应这个try setStyleSheet("QSlider::handle:horizo​​ntal {background-color: red;}");。

这就是答案,谢谢 iloXXI!

【讨论】:

    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2019-01-25
    • 2021-04-17
    • 2020-11-05
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多