qt的slider样式定制
实现上图样式滑块
滑块的圆形通过样式表实现:
this->setStyleSheet(R"(
QSlider::groove:horizontal {
background: rgb(51, 51, 51);
width: 80px;
height: 8px;
border-radius: 4px;
}
QSlider::handle:horizontal {
background: rgb(207, 207, 207);
border: 1px solid #5c5c5c;
width: 14px;
margin: -4px 0;
border-radius: 8px;
}
QSlider::handle:horizontal:hover {
background: rgb(207, 207, 207);
border: 2px solid #5c5c5c;
width: 12px;
margin: -4px 0;
border-radius: 8px;
}
)");
样式表中需要注意滑轨的高度8+滑块的margin4*2=滑块的宽度14+滑块boder1*2=16,再设置radius为16/2=8,满足上述关系,滑块才能为圆形
滑块底部的蓝色渐变条需要通过过重写slider的painter函数实现,注意绘制渐变条在滑轨两端的处理,不要绘制超过滑轨两端。
通过计算,在左右两侧各绘制渐变条即可
QSlider::paintEvent(event);
QPainter painter(this);
QStyleOptionSlider opt;
initStyleOption(&opt);
painter.setRenderHint(QPainter::Antialiasing);
QRect grooveRect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this);
QRect handleRect = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this);
int leftBoundary = ((handleRect.left() - 11) > grooveRect.left()) ? (handleRect.left() - 11) : grooveRect.left();
int rightBoundary = ((handleRect.right() + 11) < grooveRect.right()) ? (handleRect.right() + 11) : grooveRect.right();
// 绘制左侧渐变蓝色条
QLinearGradient leftGradient(leftBoundary, grooveRect.top(), handleRect.left(), grooveRect.top());
leftGradient.setColorAt(0, QColor(32, 128, 247, 0));
leftGradient.setColorAt(1, QColor(32, 128, 247, 255));
painter.fillRect(QRect(leftBoundary, grooveRect.top()+2, handleRect.left() - leftBoundary, 4), leftGradient);
// 绘制右侧渐变蓝色条
QLinearGradient rightGradient(handleRect.right(), grooveRect.top(), rightBoundary, grooveRect.top());
rightGradient.setColorAt(0, QColor(32, 128, 247, 255));
rightGradient.setColorAt(1, QColor(32, 128, 247, 0));
painter.fillRect(QRect(handleRect.right(), grooveRect.top() + 2, rightBoundary - handleRect.right(), 4), rightGradient);