40 const float periodFraction =
static_cast<float>(value) / 8.0f;
42 if (periodFraction == 0.0f) {
return "0"; }
43 if (periodFraction == 0.125f) {
return "1/8"; }
44 if (periodFraction == 0.25f) {
return "1/4"; }
45 if (periodFraction == 0.375f) {
return "3/8"; }
46 if (periodFraction == 0.5f) {
return "1/2"; }
47 if (periodFraction == -0.125f) {
return "-1/8"; }
48 if (periodFraction == -0.25f) {
return "-1/4"; }
49 if (periodFraction == -0.375f) {
return "-3/8"; }
50 if (periodFraction == -0.5f) {
return "-1/2"; }
51 return QString::number(
static_cast<double>(periodFraction),
'f', 3);
57 QSlider::paintEvent(event);
61 if (tickPosition() != QSlider::NoTicks) {
62 QPainter painter(
this);
63 painter.setFont(font());
65 const int min = minimum();
66 const int max = maximum();
67 const int interval = tickInterval();
77 const int tickCount = (max - min) / interval;
85 const int trackStart = style()->pixelMetric(QStyle::PM_SliderLength) / 2;
86 const int trackEnd = width() - trackStart;
87 const int trackWidth = trackEnd - trackStart;
88 const QFontMetrics metrics(font());
89 const int textHeight = metrics.height();
92 auto labelRectFor = [&](
const int i) {
93 const int value = min + (i * interval);
94 const double pos =
static_cast<double>(value - min) / (max - min);
95 const int xPos = trackStart +
static_cast<int>(pos * trackWidth);
97 const int textWidth = metrics.horizontalAdvance(text);
100 int textX = xPos - textWidth / 2;
101 textX = (std::max)(textX, 2);
102 textX = (std::min)(textX, width() - textWidth - 2);
103 return std::tuple(text, textX, textWidth);
106 constexpr int minLabelGap = 4;
113 const auto [maxText, maxTextX, maxTextWidth] = labelRectFor(tickCount);
115 int lastLabelRight = std::numeric_limits<int>::min();
116 for (
int i = 0; i < tickCount; ++i) {
117 const auto [text, textX, textWidth] = labelRectFor(i);
118 const bool isEndpoint = (i == 0);
119 const bool collidesWithPrevious = !isEndpoint && textX < lastLabelRight + minLabelGap;
120 const bool collidesWithMaxEndpoint = textX + textWidth + minLabelGap > maxTextX;
121 if (collidesWithPrevious || (!isEndpoint && collidesWithMaxEndpoint)) {
124 lastLabelRight = textX + textWidth;
125 painter.drawText(textX, height() - textHeight - 2, textWidth, textHeight, Qt::AlignLeft, text);
128 painter.drawText(maxTextX, height() - textHeight - 2, maxTextWidth, textHeight, Qt::AlignLeft, maxText);