刻度线在样式化的 QSlider 上消失
Posted
技术标签:
【中文标题】刻度线在样式化的 QSlider 上消失【英文标题】:tick marks disappear on styled QSlider 【发布时间】:2015-02-16 08:27:52 【问题描述】:我正在使用 Qt 5.3 并尝试设置 QSlider
的样式。但是,当我应用样式表时,刻度线会消失。有谁知道如何在不影响刻度线的情况下保持样式?
这是样式表:
QSlider::groove:horizontal
border: 1px inset #B0B0B0;
background-color: #EAEAEA;
height: 2px;
QSlider::Handle
border: 1px solid black;
background: #B0B0B0;
background-image: url(:/metal_background_small);
width: 12px;
margin: -8px 0;
QSlider::Handle:Hover
border: 1px solid black;
background: #707070;
background-image: url(:/metal_background_small);
QSlider::sub-page
/* margin: 7px 1px 7px 0px;*/
height: 2px;
background: #05bcfe;
【问题讨论】:
我注意到很多小部件,如果您开始使用样式表设置样式,您必须定义所有内容,否则它将被忽略。我不知道这是不是故意的,对我来说似乎更像是一个错误 【参考方案1】:Qt 样式表和刻度线不能很好地配合使用。最简单的解决方案是继承QSlider
并重新实现paint_event。
virtual void paintEvent(QPaintEvent *ev)
QStylePainter p(this);
QStyleOptionSlider opt;
initStyleOption(&opt);
QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
// draw tick marks
// do this manually because they are very badly behaved with style sheets
int interval = tickInterval();
if (interval == 0)
interval = pageStep();
if (tickPosition() != NoTicks)
for (int i = minimum(); i <= maximum(); i += interval)
int x = round((double)((double)((double)(i - this->minimum()) / (double)(this->maximum() - this->minimum())) * (double)(this->width() - handle.width()) + (double)(handle.width() / 2.0))) - 1;
int h = 4;
p.setPen(QColor("#a5a294"));
if (tickPosition() == TicksBothSides || tickPosition() == TicksAbove)
int y = this->rect().top();
p.drawLine(x, y, x, y + h);
if (tickPosition() == TicksBothSides || tickPosition() == TicksBelow)
int y = this->rect().bottom();
p.drawLine(x, y, x, y - h);
// draw the slider (this is basically copy/pasted from QSlider::paintEvent)
opt.subControls = QStyle::SC_SliderGroove;
p.drawComplexControl(QStyle::CC_Slider, opt);
// draw the slider handle
opt.subControls = QStyle::SC_SliderHandle;
p.drawComplexControl(QStyle::CC_Slider, opt);
【讨论】:
相关 Qt 错误报告:bugreports.qt.io/browse/QTBUG-3304, bugreports.qt.io/browse/QTBUG-3564以上是关于刻度线在样式化的 QSlider 上消失的主要内容,如果未能解决你的问题,请参考以下文章