From 0f4b1d401a27d7971a9a745ab3a7bfbeb902b27c Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Sun, 15 Nov 2026 07:00:54 +0100 Subject: [PATCH 1/5] fix: draw range sliders' bars from the style's own groove Range sliders drew the bar between their handles as a rectangle with per-OS colors, thicknesses and offsets (`_range_style.py`), which only lined up with the native groove on some OS versions. Now the bar is the style's own fill of its groove (macOS, Fusion, Windows 11, or a style sheet's sub-page) between the outer handles, or, where the style has no fill or with a custom `barColor`, a bar as thick as the style's groove. Co-Authored-By: Claude Opus 5.5 --- src/superqt/sliders/__init__.py | 2 +- src/superqt/sliders/_generic_range_slider.py | 600 +++++++++++++++++-- src/superqt/sliders/_generic_slider.py | 56 +- src/superqt/sliders/_labeled.py | 8 +- src/superqt/sliders/_range_style.py | 344 ----------- tests/zz_test_sliders/test_range_bar.py | 373 ++++++++++++ 6 files changed, 971 insertions(+), 412 deletions(-) delete mode 100644 src/superqt/sliders/_range_style.py create mode 100644 tests/zz_test_sliders/test_range_bar.py diff --git a/src/superqt/sliders/__init__.py b/src/superqt/sliders/__init__.py index e42cedc0..b0a47dc6 100644 --- a/src/superqt/sliders/__init__.py +++ b/src/superqt/sliders/__init__.py @@ -1,10 +1,10 @@ +from ._generic_slider import MONTEREY_SLIDER_STYLES_FIX from ._labeled import ( QLabeledDoubleRangeSlider, QLabeledDoubleSlider, QLabeledRangeSlider, QLabeledSlider, ) -from ._range_style import MONTEREY_SLIDER_STYLES_FIX from ._sliders import QDoubleRangeSlider, QDoubleSlider, QRangeSlider __all__ = [ diff --git a/src/superqt/sliders/_generic_range_slider.py b/src/superqt/sliders/_generic_range_slider.py index 126a4d38..3810863a 100644 --- a/src/superqt/sliders/_generic_range_slider.py +++ b/src/superqt/sliders/_generic_range_slider.py @@ -1,21 +1,56 @@ +import re from collections.abc import Sequence -from typing import TypeVar +from dataclasses import dataclass +from typing import Any, TypeVar from qtpy import QtGui -from qtpy.QtCore import Property, QEvent, QPoint, QPointF, QRect, QRectF, Qt, Signal -from qtpy.QtWidgets import QSlider, QStyle, QStyleOptionSlider, QStylePainter +from qtpy.QtCore import ( + Property, + QPoint, + QPointF, + QRect, + QRectF, + QSizeF, + Qt, + Signal, + qVersion, +) +from qtpy.QtGui import ( + QBrush, + QColor, + QGradient, + QImage, + QLinearGradient, + QPainter, + QPalette, + QRadialGradient, +) +from qtpy.QtWidgets import ( + QApplication, + QSlider, + QStyle, + QStyleOptionSlider, + QStylePainter, +) -from ._generic_slider import CC_SLIDER, SC_GROOVE, SC_HANDLE, SC_NONE, _GenericSlider -from ._range_style import ( +from ._generic_slider import ( + CC_SLIDER, MONTEREY_SLIDER_STYLES_FIX, - RangeSliderStyle, - update_styles_from_stylesheet, + SC_GROOVE, + SC_HANDLE, + SC_NONE, + SC_TICKMARKS, + _GenericSlider, ) _T = TypeVar("_T") SC_BAR = QStyle.SubControl.SC_ScrollBarSubPage +# whether Qt draws style sheets' sub-page and add-page with each handle (and so over +# the bar), as it did up to 6.10.0 (https://bugreports.qt.io/browse/QTBUG-141157) +_QT = tuple(int(n) for n in re.findall(r"\d+", qVersion())[:3]) +_PAGES_WITH_EACH_HANDLE = _QT < (6, 10, 1) class _GenericRangeSlider(_GenericSlider): @@ -40,7 +75,8 @@ class _GenericRangeSlider(_GenericSlider): slidersMoved = Signal(tuple) def __init__(self, *args, **kwargs): - self._style = RangeSliderStyle() + self._style = _BarColors() + self._macpatch = False # (whether `applyMacStylePatch` was called) super().__init__(*args, **kwargs) @@ -116,7 +152,7 @@ def applyMacStylePatch(self) -> None: see [FAQ](../faq.md#sliders-not-dragging-properly-on-macos-12) for more details. """ super().applyMacStylePatch() - self._style._macpatch = True + self._macpatch = True # ############### QtOverrides ####################### @@ -175,22 +211,9 @@ def setStyleSheet(self, styleSheet: str) -> None: def _patch_style(self, style: str): """Override to patch style options before painting.""" - # sub-page styles render on top of the lower sliders and don't work here. - if self._style._macpatch and not style: + if self._macpatch and not style: style = MONTEREY_SLIDER_STYLES_FIX - - override = f""" - \n{type(self).__name__}::sub-page:horizontal - {{background: none; border: none}} - \n{type(self).__name__}::add-page:vertical - {{background: none; border: none}} - """ - return style + override - - def event(self, ev: QEvent) -> bool: - if ev.type() == QEvent.Type.StyleChange: - update_styles_from_stylesheet(self) - return super().event(ev) + return style def mouseMoveEvent(self, ev: QtGui.QMouseEvent) -> None: if self._pressedControl == SC_BAR: @@ -210,7 +233,11 @@ def paintEvent(self, ev: QtGui.QPaintEvent) -> None: painter = QStylePainter(self) opt = self._styleOption - self._draw_groove_and_ticks(painter, opt, handle=False) + bar = self._barOption(opt, _ratio(painter)) + groove = self._drawGroove(painter, bar) + if self._should_draw_bar: + self._drawBar(painter, opt, bar, groove) + self._drawTicks(painter, opt) # (after the bar, which could cover them) self._draw_handle(painter, opt) # ############### Implementation Details ####################### @@ -237,11 +264,13 @@ def _neighbor_bound(self, val, index): val = min(_lst[index + 1] - min_dist, val) return val - def _getBarColor(self): - return self._style.brush(self._styleOption) + def _getBarColor(self) -> QBrush: + opt = self._styleOption + return self._barBrush(opt) or self._fillBrush(opt) - def _setBarColor(self, color): + def _setBarColor(self, color: Any) -> None: self._style.brush_active = color + self.update() barColor = Property(QtGui.QBrush, _getBarColor, _setBarColor) """The color of the bar between the first and last handle.""" @@ -274,48 +303,271 @@ def _handleRect( opt.sliderPosition = self._optSliderPositions[handle_index] return self.style().subControlRect(CC_SLIDER, opt, SC_HANDLE, self) - def _barRect(self, opt: QStyleOptionSlider) -> QRect: - """Return the QRect for the bar between the outer handles.""" - r_groove = self.style().subControlRect(CC_SLIDER, opt, SC_GROOVE, self) - r_bar = QRectF(r_groove) - hdl_low, hdl_high = self._handleRect(0, opt), self._handleRect(-1, opt) - - thickness = self._style.thickness(opt) - offset = self._style.offset(opt) + # Painting - if opt.orientation == Qt.Orientation.Horizontal: - r_bar.setTop(r_bar.center().y() - thickness / 2 + offset) - r_bar.setHeight(thickness) - r_bar.setLeft(hdl_low.center().x()) - r_bar.setRight(hdl_high.center().x()) + def _drawGroove(self, painter: QStylePainter, bar: QStyleOptionSlider) -> QImage: + """Draw the style's groove, without any fill; return it. + + (As the bar is drawn, by `bar`: see `_barOption`.) Styles fill the groove + from the minimum up to the handle, and some do even with the handle at the + minimum (e.g. Windows 11). Drawn upside down, that bit of fill is at the + other end: so the groove under a handle at the minimum comes from the slider + drawn upside down. But some styles fill from the same end either way: + Windows 11 up to Qt 6.10.0, and style sheets, whose sub-page is always at the + left or top, once Qt draws it with the groove + (https://bugreports.qt.io/browse/QTBUG-141608). Then that part of the groove + is the mirror image of its other end, in the colors next to it. + """ + horizontal = bar.orientation == Qt.Orientation.Horizontal + ratio = _ratio(painter) + groove = self._grooveImage(bar, bar.minimum, ratio) + flipped = QStyleOptionSlider(bar) + flipped.upsideDown = not bar.upsideDown + other = self._grooveImage(flipped, bar.minimum, ratio) + + option = QStyleOptionSlider(bar) + option.sliderPosition = option.minimum + start = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) + option.sliderPosition = option.maximum + end = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) + # (from the slider's end with the minimum to the far side of a handle at the + # minimum; and the groove between that and the other) + under, between = QRect(self.rect()), QRect(self.rect()) + if horizontal: + under.setRight(start.right()) + between.setLeft(start.right() + 1) + between.setRight(end.left() - 1) + elif bar.upsideDown: # (the minimum at the bottom) + under.setTop(start.top()) + between.setTop(end.bottom() + 1) + between.setBottom(start.top() - 1) else: - r_bar.setLeft(r_bar.center().x() - thickness / 2 + offset) - r_bar.setWidth(thickness) - r_bar.setBottom(hdl_low.center().y()) - r_bar.setTop(hdl_high.center().y()) + under.setBottom(start.bottom()) + between.setTop(start.bottom() + 1) + between.setBottom(end.top() - 1) + + mix = QPainter(groove) + mix.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) + mix.setClipRect(under) + if _crop(groove, between) == _crop(other, between): + mix.drawImage(0, 0, other) + else: # (the mirror image of the other end, then the colors next to it) + mirror = groove.copy() + next_to = QRectF(QPointF(between.topLeft()) * ratio, QSizeF(between.size())) + next_to.setSize(next_to.size() * ratio) + if horizontal: # (its first column, or row: next to that part) + mix.translate(self.width(), 0) + mix.scale(-1, 1) + next_to.setWidth(1) + else: + mix.translate(0, self.height()) + mix.scale(1, -1) + if bar.upsideDown: + next_to.setTop(next_to.bottom() - 1) + else: + next_to.setHeight(1) + mix.drawImage(0, 0, mirror) + mix.resetTransform() + mix.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceAtop) + mix.drawImage(QRectF(under), mirror, next_to) + mix.end() + painter.drawImage(0, 0, groove) + return groove + + def _drawBar( + self, + painter: QStylePainter, + opt: QStyleOptionSlider, + bar: QStyleOptionSlider, + groove: QImage, + ) -> None: + """Draw the bar between the outer handles, in the style's groove (`groove`). + + Without a `barColor`, it's the style's own fill of the groove, if it has one + (as on macOS, with Fusion and Windows 11, or a style sheet's sub-page): what + the slider drawn as the bar (`bar`, see `_barOption`) fills, up to the + handle, whichever way this one goes. Otherwise, it's a solid bar as thick as + the groove (and its fill), in the `barColor` (as is, in any state, like a + style sheet's colors) or the style's fill color. + """ + horizontal = opt.orientation == Qt.Orientation.Horizontal + ends = [self._handleRect(i, opt).center() for i in (0, -1)] + span = QRect(self.rect()) # (the part of the slider between the outer handles) + if horizontal: + span.setLeft(min(p.x() for p in ends)) + span.setRight(max(p.x() for p in ends)) + else: + span.setTop(min(p.y() for p in ends)) + span.setBottom(max(p.y() for p in ends)) + + # The groove, filled all along (as the bar is drawn), with a handle: up to + # 6.12.0, style sheets only draw pages with one. That handle, at the + # maximum, isn't part of the bar. + option = QStyleOptionSlider(bar) + option.sliderPosition = option.maximum + handle = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) + inner = _apart(span, handle, horizontal) + if inner.isEmpty(): # (the bar is under the handles) + return + empty = _crop(groove, inner) + ratio = _ratio(painter) + if (brush := self._barBrush(opt)) is None: + filled = self._grooveImage(option, option.maximum, ratio, handle=True) + filled = _crop(filled, inner) + if filled != empty: + painter.drawImage(inner.topLeft(), filled) + return + bounds = _bounds(empty) + else: # (filled without the handle, which may reach past its rect) + filled = self._grooveImage(option, option.maximum, ratio) + bounds = _bounds(_crop(filled, inner)) + if bounds.isEmpty(): # (the style draws no groove) + painter.fillRect(self._plainBar(opt, span), brush or self._fillBrush(opt)) + else: # (even if the groove is hollow, or its fill translucent) + bounds.translate(QPointF(inner.topLeft())) + rect = QRectF(span) + if horizontal: + rect.setTop(bounds.top()) + rect.setBottom(bounds.bottom()) + else: + rect.setLeft(bounds.left()) + rect.setRight(bounds.right()) + painter.fillRect(rect, brush or self._fillBrush(opt)) - return r_bar + def _barOption(self, opt: QStyleOptionSlider, ratio: float) -> QStyleOptionSlider: + """A copy of `opt`, as the bar is drawn: with the minimum at the left, or top. - # Painting + So in either orientation, the bar is the part of the groove before a handle, + where style sheets draw their sub-page. But up to Qt 6.10.0, Windows 11 fills + vertical grooves from the bottom up to the handle, whichever way the slider + goes: then the bar is drawn from the bottom. (`ratio`: the painter's.) + """ + option = QStyleOptionSlider(opt) + option.upsideDown = False + if not _PAGES_WITH_EACH_HANDLE or opt.orientation == Qt.Orientation.Horizontal: + return option + # (Style sheets then draw no pages with the groove alone: if, between handles + # at both ends, it's not the same either way, its fill is by position.) + flipped = QStyleOptionSlider(option) + flipped.upsideDown = True + top, bottom = QStyleOptionSlider(option), QStyleOptionSlider(flipped) + top.sliderPosition = bottom.sliderPosition = opt.minimum + top_end = self.style().subControlRect(CC_SLIDER, top, SC_HANDLE, self) + bottom_end = self.style().subControlRect(CC_SLIDER, bottom, SC_HANDLE, self) + between = QRect(self.rect()) + between.setTop(top_end.bottom() + 1) + between.setBottom(bottom_end.top() - 1) + groove = self._grooveImage(option, opt.minimum, ratio) + other = self._grooveImage(flipped, opt.minimum, ratio) + if _crop(groove, between) != _crop(other, between): + option.upsideDown = True + return option + + def _drawTicks(self, painter: QStylePainter, opt: QStyleOptionSlider) -> None: + if opt.tickPosition != QSlider.TickPosition.NoTicks: + opt.subControls = SC_TICKMARKS + painter.drawComplexControl(CC_SLIDER, opt) + self._draw_qss_ticks(painter, opt) - def _drawBar(self, painter: QStylePainter, opt: QStyleOptionSlider): - brush = self._style.brush(opt) - r_bar = self._barRect(opt) - if isinstance(brush, QtGui.QGradient): - brush.setStart(r_bar.topLeft()) - brush.setFinalStop(r_bar.bottomRight()) - painter.setPen(self._style.pen(opt)) - painter.setBrush(brush) - painter.drawRect(r_bar) + def _plainBar(self, opt: QStyleOptionSlider, span: QRect) -> QRectF: + """A 4px bar across `span`, centered on the style's groove.""" + groove = self.style().subControlRect(CC_SLIDER, opt, SC_GROOVE, self) + bar = QRectF(span) + if opt.orientation == Qt.Orientation.Horizontal: + bar.setTop(groove.center().y() - 2) + bar.setHeight(4) + else: + bar.setLeft(groove.center().x() - 2) + bar.setWidth(4) + return bar - def _draw_handle(self, painter: QStylePainter, opt: QStyleOptionSlider): - if self._should_draw_bar: - self._drawBar(painter, opt) + def _grooveImage( + self, + opt: QStyleOptionSlider, + position: int, + ratio: float, + style: QStyle | None = None, + handle: bool = False, + ) -> QImage: + """The style's groove (and `handle`), filled up to `position`.""" + option = QStyleOptionSlider(opt) + option.subControls = SC_GROOVE | SC_HANDLE if handle else SC_GROOVE + option.sliderPosition = position + return self._sliderImage(option, ratio, style) + + def _sliderImage( + self, opt: QStyleOptionSlider, ratio: float, style: QStyle | None = None + ) -> QImage: + """What the style draws for `opt`, as an image of the whole slider. + + (Of the whole slider: the macOS style mirrors inverted sliders around the + slider's rect, and ignores clipping.) `ratio` is the image's pixel ratio. + """ + image = QImage(self.size() * ratio, QImage.Format.Format_ARGB32_Premultiplied) + image.setDevicePixelRatio(ratio) + image.fill(Qt.GlobalColor.transparent) + painter = QPainter(image) + (style or self.style()).drawComplexControl(CC_SLIDER, opt, painter, self) + painter.end() + return image + + def _fillBrush(self, opt: QStyleOptionSlider) -> QBrush: + """The color that the style fills slider grooves with (else the palette's). + + (The palette's accent, grayed if disabled or if it's the window's color.) + + It's read from a groove that the style draws without tick marks (with them, + macOS doesn't fill it), filled up to its maximum. (Not the style sheet's style, + which may not fill it: the app's, unless the slider has its own.) + """ + style = self.style() + if not self.testAttribute(Qt.WidgetAttribute.WA_SetStyle): + style = QApplication.style() + option = QStyleOptionSlider(opt) + option.tickPosition = QSlider.TickPosition.NoTicks + ratio = self.devicePixelRatioF() # (any: it's only for its color) + empty = self._grooveImage(option, option.minimum, ratio, style) + full = self._grooveImage(option, option.maximum, ratio, style) + center = _bounds(full).center() * ratio + x, y = int(center.x()), int(center.y()) + if full.valid(x, y) and full.pixel(x, y) != empty.pixel(x, y): + return QBrush(full.pixelColor(x, y)) + palette = opt.palette + grayed = palette.brush( + QPalette.ColorGroup.Disabled, QPalette.ColorRole.WindowText + ) + if palette.currentColorGroup() == QPalette.ColorGroup.Disabled: + return grayed + role = getattr(QPalette.ColorRole, "Accent", QPalette.ColorRole.Highlight) + brush = palette.brush(role) # (`Accent` is new in Qt 6.6) + # (Qt's Windows palettes have it in the window's color in inactive windows) + if brush.color() == palette.color(QPalette.ColorRole.Window): + return grayed + return brush + + def _barBrush(self, opt: QStyleOptionSlider) -> QBrush | None: + """The custom color of the bar, in the slider's current state (if any).""" + group = opt.palette.currentColorGroup() + colors = self._style + if group == QPalette.ColorGroup.Disabled: + color = colors.brush_disabled + elif group == QPalette.ColorGroup.Inactive: + color = colors.brush_inactive or colors.brush_active + else: + color = colors.brush_active + return _to_brush(color) + def _draw_handle(self, painter: QStylePainter, opt: QStyleOptionSlider): opt.subControls = SC_HANDLE pidx = self._pressedIndex if self._pressedControl == SC_HANDLE else -1 hidx = self._hoverIndex if self._hoverControl == SC_HANDLE else -1 - for idx, pos in enumerate(self._optSliderPositions): + positions = self._optSliderPositions + # (the handle at the left, or top) + first = (max if opt.upsideDown else min)( + range(len(positions)), key=positions.__getitem__ + ) + pages = self._pagesWithHandles(painter, opt) + for idx, pos in enumerate(positions): opt.sliderPosition = pos # make pressed handles appear sunken if idx == pidx: @@ -323,7 +575,100 @@ def _draw_handle(self, painter: QStylePainter, opt: QStyleOptionSlider): else: opt.state = opt.state & ~QStyle.StateFlag.State_Sunken opt.activeSubControls = SC_HANDLE if idx == hidx else SC_NONE - painter.drawComplexControl(CC_SLIDER, opt) + self._drawHandle(painter, opt, pages, first=idx == first) + + def _pagesWithHandles( + self, painter: QStylePainter, opt: QStyleOptionSlider + ) -> tuple[bool, bool]: + """Whether the style draws a page before each handle, and one after it. + + (Style sheets' sub-page and add-page, which Qt draws with each handle up to + 6.10.0: https://bugreports.qt.io/browse/QTBUG-141157.) With a handle at two + places, off screen: a page runs from an end of the groove to the handle, so + it grows or shrinks as the handle moves, while a handle, and its shadow or + glow (however far it reaches), moves with it. + """ + if not _PAGES_WITH_EACH_HANDLE: + return False, False + ratio = _ratio(painter) + quarter = (opt.maximum - opt.minimum) // 4 + one = self._pastHandle(opt, opt.minimum + quarter, ratio) + other = self._pastHandle(opt, opt.maximum - quarter, ratio) + return abs(one[0] - other[0]) > 1, abs(one[1] - other[1]) > 1 + + def _pastHandle( + self, opt: QStyleOptionSlider, position: int, ratio: float + ) -> tuple[float, float]: + """How far what the style draws for a handle at `position` reaches past it. + + (Before it, and after it: at its left and right, or top and bottom.) + """ + option = QStyleOptionSlider(opt) + option.subControls = SC_HANDLE + option.sliderPosition = position + drawn = _bounds(self._sliderImage(option, ratio)) + if drawn.isEmpty(): + return 0.0, 0.0 + rect = QRectF(self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self)) + if opt.orientation == Qt.Orientation.Horizontal: + return rect.left() - drawn.left(), drawn.right() - rect.right() + return rect.top() - drawn.top(), drawn.bottom() - rect.bottom() + + def _drawHandle( + self, + painter: QStylePainter, + opt: QStyleOptionSlider, + pages: tuple[bool, bool] = (False, False), + first: bool = False, + ) -> None: + """Draw a handle, without the style sheet's sub-page and add-page (`pages`). + + Up to 6.10.0, Qt draws them with each handle, over the bar: then only the + handle's own rect is drawn (https://bugreports.qt.io/browse/QTBUG-141157). + The pages show in it around a round handle, in the groove. With a page on one + side, only what the handle's mirror image covers too is drawn there. With + pages on both sides, they're kept on the right sides: the bar's (the + sub-page's) is before each handle, at its left or top. So the `first` handle, + at the left or top, with the bar on its other side, is drawn upside down, + then mirrored back. + """ + if any(pages): # (style sheet handles, which don't blend with what's behind) + ratio = _ratio(painter) + rect = self.style().subControlRect(CC_SLIDER, opt, SC_HANDLE, self) + if all(pages) and first: + image = _crop(self._mirroredHandle(opt, rect, ratio), rect) + else: + image = _crop(self._sliderImage(opt, ratio), rect) + if not all(pages): + groove = self.style().subControlRect(CC_SLIDER, opt, SC_GROOVE, self) + horizontal = opt.orientation == Qt.Orientation.Horizontal + band = groove.translated(-rect.topLeft()) + image = _symmetric(image, band, horizontal) + painter.drawImage(rect.topLeft(), image) + return + # (directly: native handles may blend with what's behind them, e.g. on macOS) + painter.drawComplexControl(CC_SLIDER, opt) + + def _mirroredHandle( + self, opt: QStyleOptionSlider, rect: QRect, ratio: float + ) -> QImage: + """The handle in `rect`, drawn upside down, then mirrored back onto `rect`.""" + option = QStyleOptionSlider(opt) + option.upsideDown = not opt.upsideDown + there = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) + image = QImage(self.size() * ratio, QImage.Format.Format_ARGB32_Premultiplied) + image.setDevicePixelRatio(ratio) + image.fill(Qt.GlobalColor.transparent) + painter = QPainter(image) + if opt.orientation == Qt.Orientation.Horizontal: + painter.translate(rect.x() + there.x() + rect.width(), 0) + painter.scale(-1, 1) + else: + painter.translate(0, rect.y() + there.y() + rect.height()) + painter.scale(1, -1) + self.style().drawComplexControl(CC_SLIDER, option, painter, self) + painter.end() + return image def _updateHoverControl(self, pos): old_hover = self._hoverControl, self._hoverIndex @@ -392,3 +737,136 @@ def _spreadAllPositions(self, shrink=False, gain=1.1, ref=None) -> None: gain = 1 / gain center = abs(ref[-1] + ref[0]) / 2 self.setSliderPosition([((i - center) * gain) + center for i in ref]) + + +@dataclass +class _BarColors: + """Custom colors of the bar, for each state (`None`: the style's own). + + `barColor` sets `brush_active`, which is also used for inactive windows. (It's the + slider's `_style`, whose attributes some projects set directly.) + """ + + brush_active: Any = None + brush_inactive: Any = None + brush_disabled: Any = None + + +def _ratio(painter: QPainter) -> float: + """The scale of what the painter paints on (e.g. 2 for a 2x image). + + (Not the widget's ratio: when rendered to an image, it's the screen's.) + """ + transform = painter.deviceTransform() + return max(abs(transform.m11()), abs(transform.m22())) or 1.0 + + +def _apart(rect: QRect, other: QRect, horizontal: bool) -> QRect: + """The part of `rect` that's not on `other`, on its side (along the slider).""" + if not rect.intersects(other): + return QRect(rect) + out = QRect(rect) + if horizontal and other.center().x() >= rect.center().x(): + out.setRight(other.left() - 1) + elif horizontal: + out.setLeft(other.right() + 1) + elif other.center().y() >= rect.center().y(): + out.setBottom(other.top() - 1) + else: + out.setTop(other.bottom() + 1) + return out + + +def _crop(image: QImage, rect: QRect) -> QImage: + """The part of `image` in `rect` (in logical pixels).""" + ratio = image.devicePixelRatio() + pixels = QRectF(QPointF(rect.topLeft()) * ratio, QSizeF(rect.size()) * ratio) + part = image.copy(pixels.toAlignedRect()) + part.setDevicePixelRatio(ratio) + return part + + +def _symmetric(image: QImage, rect: QRect, horizontal: bool) -> QImage: + """`image`, in `rect`, only where its mirror image (along the slider) is too.""" + out = QImage(image) + painter = QPainter(out) + painter.setCompositionMode(QPainter.CompositionMode.CompositionMode_DestinationIn) + painter.setClipRect(rect) + ratio = image.devicePixelRatio() + if horizontal: + painter.translate(image.width() / ratio, 0) + painter.scale(-1, 1) + else: + painter.translate(0, image.height() / ratio) + painter.scale(1, -1) + painter.drawImage(0, 0, image) + painter.end() + return out + + +def _bounds(image: QImage) -> QRectF: + """The bounds of the image's pixels that aren't transparent (in logical pixels). + + (Even faint ones: the macOS groove is a black overlay with an alpha of ~5%.) + """ + alpha = image.convertToFormat(QImage.Format.Format_Alpha8) + bits = alpha.constBits() + if hasattr(bits, "setsize"): # (PyQt) + bits.setsize(alpha.sizeInBytes()) + data, stride, width = bytes(bits), alpha.bytesPerLine(), alpha.width() + rows, left, right = [], width, -1 + for y in range(alpha.height()): + row = data[y * stride : y * stride + width] + if visible := row.lstrip(b"\0"): + rows.append(y) + left = min(left, width - len(visible)) + right = max(right, len(row.rstrip(b"\0")) - 1) + if not rows: + return QRectF() + ratio = image.devicePixelRatio() + pixels = QRectF(left, rows[0], right - left + 1, rows[-1] - rows[0] + 1) + return QRectF(pixels.topLeft() / ratio, pixels.size() / ratio) + + +def _to_brush(color: Any) -> QBrush | None: + """`color` as a brush: a QBrush, QColor, QGradient, or a string (see `_parse`).""" + if color is None or isinstance(color, QBrush): + return color + if isinstance(color, str): + color = _parse(color) + return None if color is None else QBrush(color) + return QBrush(color) # (a QColor, QGradient, or Qt.GlobalColor) + + +_NUM = r"(\d*\.?\d+)" +_RGBA = re.compile(r"rgba?\((\d+),\s*(\d+),\s*(\d+),?\s*(\d+)?\)") +_LINEAR = re.compile( + rf"qlineargradient\(x1:\s*{_NUM},\s*y1:\s*{_NUM},\s*x2:\s*{_NUM},\s*" + rf"y2:\s*{_NUM},\s*stop:0\s*(\S+),.*stop:1\s*(\S+)\)" +) +_RADIAL = re.compile( + rf"qradialgradient\(cx:\s*{_NUM},\s*cy:\s*{_NUM},\s*radius:\s*{_NUM},\s*" + rf"fx:\s*{_NUM},\s*fy:\s*{_NUM},\s*stop:0\s*(\S+),.*stop:1\s*(\S+)\)" +) + + +def _parse(color: str) -> QColor | QGradient | None: + """A color name, `"#rrggbb"`, `"rgba(r, g, b, a)"`, or a QSS gradient.""" + if (qcolor := QColor(color)).isValid(): + return qcolor + if match := _RGBA.search(color): + return QColor(*(int(x) if x else 255 for x in match.groups())) + gradient: QGradient + if match := _LINEAR.search(color): + *coords, stop0, stop1 = match.groups() + gradient = QLinearGradient(*map(float, coords)) + elif match := _RADIAL.search(color): + *coords, stop0, stop1 = match.groups() + gradient = QRadialGradient(*map(float, coords)) + else: + return None + # (coordinates are relative to the bar, as in style sheets) + gradient.setCoordinateMode(QGradient.CoordinateMode.ObjectBoundingMode) + gradient.setColorAt(0, QColor(stop0)) + gradient.setColorAt(1, QColor(stop1)) + return gradient diff --git a/src/superqt/sliders/_generic_slider.py b/src/superqt/sliders/_generic_slider.py index 059fd38b..f825a329 100644 --- a/src/superqt/sliders/_generic_slider.py +++ b/src/superqt/sliders/_generic_slider.py @@ -34,8 +34,6 @@ QStylePainter, ) -from ._range_style import MONTEREY_SLIDER_STYLES_FIX - _T = TypeVar("_T") SC_NONE = QStyle.SubControl.SC_None @@ -46,6 +44,58 @@ CC_SLIDER = QStyle.ComplexControl.CC_Slider QOVERFLOW = 2**31 - 1 +# a fix for https://bugreports.qt.io/browse/QTBUG-98093 + +MONTEREY_SLIDER_STYLES_FIX = """ +/* MONTEREY_SLIDER_STYLES_FIX */ + +QSlider::groove { + background: #DFDFDF; + border: 1px solid #DBDBDB; + border-radius: 2px; +} +QSlider::groove:horizontal { + height: 2px; + margin: 2px; +} +QSlider::groove:vertical { + width: 2px; + margin: 2px 0 6px 0; +} + + +QSlider::handle { + background: white; + border: 0.5px solid #DADADA; + width: 19.5px; + height: 19.5px; + border-radius: 10.5px; +} +QSlider::handle:horizontal { + margin: -10px -2px; +} +QSlider::handle:vertical { + margin: -2px -10px; +} + +QSlider::handle:pressed { + background: #F0F0F0; +} + +QSlider::sub-page:horizontal { + background: #0981FE; + border-radius: 2px; + margin: 2px; + height: 2px; +} +QSlider::add-page:vertical { + background: #0981FE; + border-radius: 2px; + margin: 2px 0 6px 0; + width: 2px; +} +""".strip() + # whether to use the MONTEREY_SLIDER_STYLES_FIX QSS hack # for fixing sliders on macos>=12 with QT < 6 # https://bugreports.qt.io/browse/QTBUG-98093 @@ -402,7 +452,9 @@ def _draw_groove_and_ticks(self, painter, opt, handle=True): if opt.tickPosition != QSlider.TickPosition.NoTicks: opt.subControls |= SC_TICKMARKS painter.drawComplexControl(CC_SLIDER, opt) + self._draw_qss_ticks(painter, opt) + def _draw_qss_ticks(self, painter, opt): if ( opt.tickPosition != QSlider.TickPosition.NoTicks and "MONTEREY_SLIDER_STYLES_FIX" in self.styleSheet() diff --git a/src/superqt/sliders/_labeled.py b/src/superqt/sliders/_labeled.py index 81b2d4aa..fd750ed7 100644 --- a/src/superqt/sliders/_labeled.py +++ b/src/superqt/sliders/_labeled.py @@ -521,10 +521,10 @@ def resizeEvent(self, a0: Any) -> None: EdgeLabelMode = EdgeLabelMode def _getBarColor(self) -> QtGui.QBrush: - return self._slider._style.brush(self._slider._styleOption) + return self._slider.barColor def _setBarColor(self, color: str) -> None: - self._slider._style.brush_active = color + self._slider.barColor = color barColor = Property(QtGui.QBrush, _getBarColor, _setBarColor) """The color of the bar between the first and last handle.""" @@ -681,10 +681,10 @@ def setDecimals(self, prec: int) -> None: lbl.setDecimals(prec) def _getBarColor(self) -> QtGui.QBrush: - return self._slider._style.brush(self._slider._styleOption) + return self._slider.barColor def _setBarColor(self, color: str) -> None: - self._slider._style.brush_active = color + self._slider.barColor = color barColor = Property(QtGui.QBrush, _getBarColor, _setBarColor) """The color of the bar between the first and last handle.""" diff --git a/src/superqt/sliders/_range_style.py b/src/superqt/sliders/_range_style.py deleted file mode 100644 index 9e99b794..00000000 --- a/src/superqt/sliders/_range_style.py +++ /dev/null @@ -1,344 +0,0 @@ -from __future__ import annotations - -import platform -import re -from dataclasses import dataclass, replace -from typing import TYPE_CHECKING - -from qtpy.QtCore import Qt -from qtpy.QtGui import ( - QBrush, - QColor, - QGradient, - QLinearGradient, - QPalette, - QRadialGradient, -) -from qtpy.QtWidgets import QApplication, QSlider, QStyleOptionSlider - -if TYPE_CHECKING: - from ._generic_range_slider import _GenericRangeSlider - - -@dataclass -class RangeSliderStyle: - brush_active: str | None = None - brush_inactive: str | None = None - brush_disabled: str | None = None - pen_active: str | None = None - pen_inactive: str | None = None - pen_disabled: str | None = None - vertical_thickness: float | None = None - horizontal_thickness: float | None = None - tick_offset: float | None = None - tick_bar_alpha: float | None = None - v_offset: float | None = None - h_offset: float | None = None - has_stylesheet: bool = False - _macpatch: bool = False - - def brush(self, opt: QStyleOptionSlider) -> QBrush: - cg = opt.palette.currentColorGroup() - attr = { - QPalette.ColorGroup.Active: "brush_active", # 0 - QPalette.ColorGroup.Disabled: "brush_disabled", # 1 - QPalette.ColorGroup.Inactive: "brush_inactive", # 2 - }[cg] - _val = getattr(self, attr) - if not _val: - if self.has_stylesheet: - # if someone set a general style sheet but didn't specify - # :active, :inactive, etc... then Qt just uses whatever they - # DID specify - for i in ("active", "inactive", "disabled"): - _val = getattr(self, f"brush_{i}") - if _val: - break - else: - _val = getattr(SYSTEM_STYLE, attr) - - if _val is None: - return QBrush() - - if isinstance(_val, str): - val = QColor(_val) - if not val.isValid(): - val = parse_color(_val, default_attr=attr) - else: - val = _val - - if opt.tickPosition != QSlider.TickPosition.NoTicks: - val.setAlphaF(self.tick_bar_alpha or SYSTEM_STYLE.tick_bar_alpha) - - return QBrush(val) - - def pen(self, opt: QStyleOptionSlider) -> Qt.PenStyle | QColor: - cg = opt.palette.currentColorGroup() - attr = { - QPalette.ColorGroup.Active: "pen_active", # 0 - QPalette.ColorGroup.Disabled: "pen_disabled", # 1 - QPalette.ColorGroup.Inactive: "pen_inactive", # 2 - }[cg] - val = getattr(self, attr) - if not val and not self.has_stylesheet: - val = getattr(SYSTEM_STYLE, attr) - if not val: - return Qt.PenStyle.NoPen - if isinstance(val, str): - val = QColor(val) - if opt.tickPosition != QSlider.TickPosition.NoTicks: - val.setAlphaF(self.tick_bar_alpha or SYSTEM_STYLE.tick_bar_alpha) - return val - - def offset(self, opt: QStyleOptionSlider) -> int: - off = 0 - if not self.has_stylesheet: - tp = opt.tickPosition - if opt.orientation == Qt.Orientation.Horizontal: - if not self._macpatch: - off += self.h_offset or SYSTEM_STYLE.h_offset or 0 - else: - off += self.v_offset or SYSTEM_STYLE.v_offset or 0 - if tp == QSlider.TickPosition.TicksAbove: - off += self.tick_offset or SYSTEM_STYLE.tick_offset - elif tp == QSlider.TickPosition.TicksBelow: - off -= self.tick_offset or SYSTEM_STYLE.tick_offset - return off - - def thickness(self, opt: QStyleOptionSlider) -> float: - if opt.orientation == Qt.Orientation.Horizontal: - return self.horizontal_thickness or SYSTEM_STYLE.horizontal_thickness - else: - return self.vertical_thickness or SYSTEM_STYLE.vertical_thickness - - -# ########## System-specific default styles ############ - -BASE_STYLE = RangeSliderStyle( - brush_active="#3B88FD", - brush_inactive="#8F8F8F", - brush_disabled="#BBBBBB", - pen_active=None, - pen_inactive=None, - pen_disabled=None, - vertical_thickness=4, - horizontal_thickness=4, - tick_offset=0, - tick_bar_alpha=0.3, - v_offset=0, - h_offset=0, - has_stylesheet=False, -) - -CATALINA_STYLE = replace( - BASE_STYLE, - brush_active="#3B88FD", - brush_inactive="#8F8F8F", - brush_disabled="#D2D2D2", - horizontal_thickness=3, - vertical_thickness=3, - tick_bar_alpha=0.3, - tick_offset=4, -) - -# I can no longer reproduce the cases in which this was necessary -# if QT_VERSION and int(QT_VERSION.split(".")[0]) == 6: -# CATALINA_STYLE = replace(CATALINA_STYLE, tick_offset=2) - -BIG_SUR_STYLE = replace( - CATALINA_STYLE, - brush_active="#0A81FE", - brush_inactive="#D5D5D5", - brush_disabled="#E6E6E6", - tick_offset=0, - horizontal_thickness=4, - vertical_thickness=4, - h_offset=-2, - tick_bar_alpha=0.2, -) - -# I can no longer reproduce the cases in which this was necessary -# if QT_VERSION and int(QT_VERSION.split(".")[0]) == 6: -# BIG_SUR_STYLE = replace(BIG_SUR_STYLE, tick_offset=-3) - -WINDOWS_STYLE = replace( - BASE_STYLE, - brush_active="#550179D7", - brush_inactive="#330179D7", - brush_disabled=None, -) - -LINUX_STYLE = replace( - BASE_STYLE, - brush_active="#44A0D9", - brush_inactive="#44A0D9", - brush_disabled="#44A0D9", - pen_active="#286384", - pen_inactive="#286384", - pen_disabled="#286384", -) - -SYSTEM = platform.system() -if SYSTEM == "Darwin": - if int(platform.mac_ver()[0].split(".", maxsplit=1)[0]) >= 11: - SYSTEM_STYLE = BIG_SUR_STYLE - else: - SYSTEM_STYLE = CATALINA_STYLE -elif SYSTEM == "Windows": - SYSTEM_STYLE = WINDOWS_STYLE -elif SYSTEM == "Linux": - SYSTEM_STYLE = LINUX_STYLE -else: - SYSTEM_STYLE = BASE_STYLE - - -# ################ Stylesheet parsing logic ######################## - -qlineargrad_pattern = re.compile( - r""" - qlineargradient\( - x1:\s*(?P\d*\.?\d+),\s* - y1:\s*(?P\d*\.?\d+),\s* - x2:\s*(?P\d*\.?\d+),\s* - y2:\s*(?P\d*\.?\d+),\s* - stop:0\s*(?P\S+),.* - stop:1\s*(?P\S+) - \)""", - re.X, -) - -qradial_pattern = re.compile( - r""" - qradialgradient\( - cx:\s*(?P\d*\.?\d+),\s* - cy:\s*(?P\d*\.?\d+),\s* - radius:\s*(?P\d*\.?\d+),\s* - fx:\s*(?P\d*\.?\d+),\s* - fy:\s*(?P\d*\.?\d+),\s* - stop:0\s*(?P\S+),.* - stop:1\s*(?P\S+) - \)""", - re.X, -) - -rgba_pattern = re.compile( - r""" - rgba?\( - (?P\d+),\s* - (?P\d+),\s* - (?P\d+),?\s*(?P\d+)?\) - """, - re.X, -) - - -def parse_color(color: str, default_attr: str) -> QColor | QGradient: - qc = QColor(color) - if qc.isValid(): - return qc - - match = rgba_pattern.search(color) - if match: - rgba = [int(x) if x else 255 for x in match.groups()] - return QColor(*rgba) - - # try linear gradient: - match = qlineargrad_pattern.search(color) - grad: QGradient - if match: - grad = QLinearGradient(*(float(i) for i in match.groups()[:4])) - grad.setColorAt(0, QColor(match.groupdict()["stop0"])) - grad.setColorAt(1, QColor(match.groupdict()["stop1"])) - return grad - - # try linear gradient: - match = qradial_pattern.search(color) - if match: - grad = QRadialGradient(*(float(i) for i in match.groups()[:5])) - grad.setColorAt(0, QColor(match.groupdict()["stop0"])) - grad.setColorAt(1, QColor(match.groupdict()["stop1"])) - return grad - - # fallback to dark gray - return QColor(getattr(SYSTEM_STYLE, default_attr)) - - -def update_styles_from_stylesheet(obj: _GenericRangeSlider) -> None: - qss: str = obj.styleSheet() - - parent = obj.parent() - while parent and hasattr(parent, "styleSheet"): - qss = parent.styleSheet() + qss - parent = parent.parent() - qss = QApplication.instance().styleSheet() + qss - if not qss: - return - if MONTEREY_SLIDER_STYLES_FIX in qss: - qss = qss.replace(MONTEREY_SLIDER_STYLES_FIX, "") - obj._style._macpatch = True - else: - obj._style._macpatch = False - - # Find bar height/width - for orient, dim in (("horizontal", "height"), ("vertical", "width")): - match = re.search(rf"Slider::groove:{orient}\s*{{\s*([^}}]+)}}", qss, re.S) - if match: - for line in reversed(match.groups()[0].splitlines()): - bgrd = re.search(rf"{dim}\s*:\s*(\d+)", line) - if bgrd: - thickness = float(bgrd.groups()[-1]) - setattr(obj._style, f"{orient}_thickness", thickness) - obj._style.has_stylesheet = True - - -# a fix for https://bugreports.qt.io/browse/QTBUG-98093 - -MONTEREY_SLIDER_STYLES_FIX = """ -/* MONTEREY_SLIDER_STYLES_FIX */ - -QSlider::groove { - background: #DFDFDF; - border: 1px solid #DBDBDB; - border-radius: 2px; -} -QSlider::groove:horizontal { - height: 2px; - margin: 2px; -} -QSlider::groove:vertical { - width: 2px; - margin: 2px 0 6px 0; -} - - -QSlider::handle { - background: white; - border: 0.5px solid #DADADA; - width: 19.5px; - height: 19.5px; - border-radius: 10.5px; -} -QSlider::handle:horizontal { - margin: -10px -2px; -} -QSlider::handle:vertical { - margin: -2px -10px; -} - -QSlider::handle:pressed { - background: #F0F0F0; -} - -QSlider::sub-page:horizontal { - background: #0981FE; - border-radius: 2px; - margin: 2px; - height: 2px; -} -QSlider::add-page:vertical { - background: #0981FE; - border-radius: 2px; - margin: 2px 0 6px 0; - width: 2px; -} -""".strip() diff --git a/tests/zz_test_sliders/test_range_bar.py b/tests/zz_test_sliders/test_range_bar.py new file mode 100644 index 00000000..596922ab --- /dev/null +++ b/tests/zz_test_sliders/test_range_bar.py @@ -0,0 +1,373 @@ +"""The bar between the handles of range sliders: always visible, and its color.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest +from qtpy.QtCore import QPoint, QRect, Qt +from qtpy.QtGui import QBrush, QColor, QGradient, QImage, QPainter, QPalette +from qtpy.QtWidgets import QProxyStyle, QSlider, QStyle, QStyleFactory + +from superqt import QLabeledDoubleRangeSlider, QLabeledRangeSlider, QRangeSlider +from superqt.sliders._generic_range_slider import _PAGES_WITH_EACH_HANDLE +from superqt.sliders._generic_slider import CC_SLIDER, SC_GROOVE, SC_HANDLE + +if TYPE_CHECKING: + from pytestqt.qtbot import QtBot + +H, V = Qt.Orientation.Horizontal, Qt.Orientation.Vertical +TICKS = [QSlider.TickPosition.NoTicks, QSlider.TickPosition.TicksBelow] + + +def _bar_visible(slider: QRangeSlider) -> bool: + """Whether the middle of the bar looks different from both ends of the slider.""" + image: QImage = slider.grab().toImage() + horizontal = slider.orientation() == H + ratio = image.width() / slider.width() + centers = [slider._handleRect(i).center() for i in (0, -1)] + mid = sum((c.x() if horizontal else c.y()) for c in centers) / 2 * ratio + size = image.width() if horizontal else image.height() + + def line(at: float) -> list[int]: + at = round(at) + if horizontal: + return [image.pixel(at, y) for y in range(image.height())] + return [image.pixel(x, at) for x in range(image.width())] + + # (away from the ends: some styles fill a bit of the groove at the minimum) + return all(line(mid) != line(end) for end in (size * 0.1, size * 0.9)) + + +@pytest.mark.parametrize("style", QStyleFactory.keys()) +@pytest.mark.parametrize("orientation", [H, V]) +@pytest.mark.parametrize("ticks", TICKS) +def test_bar_is_visible( + qtbot: QtBot, style: str, orientation: Qt.Orientation, ticks: QSlider.TickPosition +) -> None: + slider = QRangeSlider(orientation) + qtbot.addWidget(slider) + qstyle = QStyleFactory.create(style) # (the widget doesn't own it) + slider.setStyle(qstyle) + slider.setTickPosition(ticks) + slider.resize(200, 30) if orientation == H else slider.resize(30, 200) + slider.setValue((30, 70)) + assert _bar_visible(slider) + + slider.setInvertedAppearance(True) + assert _bar_visible(slider) + + slider.barColor = "red" + assert _bar_visible(slider) + + +def test_bar_with_style_sheet(qtbot: QtBot) -> None: + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet( + "QSlider::groove:horizontal { height: 6px; background: gray; }" + ) + slider.resize(200, 30) + slider.setValue((30, 70)) + assert _bar_visible(slider) + + +def test_bar_from_style_sheet_sub_page(qtbot: QtBot) -> None: + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet( + "QSlider::groove:horizontal { height: 6px; background: gray; }" + "QSlider::sub-page:horizontal { background: #00ff00; }" + ) + slider.resize(200, 30) + slider.setValue((30, 70)) + image = slider.grab().toImage() + ratio = image.width() / slider.width() + middle = slider.rect().center() + color = image.pixelColor(round(middle.x() * ratio), round(middle.y() * ratio)) + assert color == QColor("#00ff00") + + +PAGES = """ +QSlider::groove:horizontal { height: 6px; background: gray; } +QSlider::groove:vertical { width: 6px; background: gray; } +QSlider::handle:horizontal { width: 10px; background: white; } +QSlider::handle:vertical { height: 10px; background: white; } +QSlider::sub-page { background: #00ff00; } +QSlider::add-page { background: #0000ff; } +""" + + +@pytest.mark.parametrize("orientation", [H, V]) +@pytest.mark.parametrize("inverted", [False, True]) +def test_style_sheet_fill_is_the_bar( + qtbot: QtBot, orientation: Qt.Orientation, inverted: bool +) -> None: + # (the sub-page, before the handle, at the left or top: in either orientation) + slider = QRangeSlider(orientation) + qtbot.addWidget(slider) + slider.setStyleSheet(PAGES) + slider.setInvertedAppearance(inverted) + slider.resize(200, 30) if orientation == H else slider.resize(30, 200) + slider.setValue((30, 70)) + fill = QColor("#00ff00") + assert _bar_center(slider) == fill + assert fill not in _before_first_handle(slider) + assert fill not in _after_last_handle(slider) + + +class _FillsFromMinimum(QProxyStyle): + """Fusion, with red over the groove from the minimum up to the handle. + + If `follows`, from the minimum wherever it is, like Windows 11; or else, from + the left or bottom (the minimum unless inverted), like Windows 11 up to 6.10.0. + """ + + def __init__(self, follows: bool) -> None: + super().__init__("Fusion") + self.follows = follows + + def drawComplexControl(self, control, option, painter, widget=None) -> None: + super().drawComplexControl(control, option, painter, widget) + if control != CC_SLIDER or not option.subControls & SC_GROOVE: + return + groove = self.subControlRect(control, option, SC_GROOVE, widget) + center = self.subControlRect(control, option, SC_HANDLE, widget).center() + fill = QRect(groove) + if option.orientation == H: + inverted = self.follows and option.upsideDown + fill.setLeft(center.x()) if inverted else fill.setRight(center.x()) + else: + inverted = self.follows and not option.upsideDown + fill.setBottom(center.y()) if inverted else fill.setTop(center.y()) + painter.fillRect(fill, QColor("#ff0000")) + + +@pytest.mark.parametrize("follows", [True, False]) +@pytest.mark.parametrize("orientation", [H, V]) +@pytest.mark.parametrize("inverted", [False, True]) +def test_no_fill_outside_the_bar( + qtbot: QtBot, follows: bool, orientation: Qt.Orientation, inverted: bool +) -> None: + if not follows and orientation == V and not _PAGES_WITH_EACH_HANDLE: + # (then it's drawn like a style sheet: the bar is the part before a handle) + pytest.skip("only Windows 11 up to Qt 6.10.0 fills from the bottom either way") + slider = QRangeSlider(orientation) + qtbot.addWidget(slider) + style = _FillsFromMinimum(follows) # (the widget doesn't own it) + slider.setStyle(style) + slider.setInvertedAppearance(inverted) + slider.resize(200, 30) if orientation == H else slider.resize(30, 200) + slider.setValue((30, 70)) + assert _bar_center(slider) == QColor("#ff0000") + assert QColor("#ff0000") not in _before_first_handle(slider) + assert QColor("#ff0000") not in _after_last_handle(slider) + + +class _Glow(QProxyStyle): + """Fusion, with a glow around handles, reaching far past them.""" + + def drawComplexControl(self, control, option, painter, widget=None) -> None: + super().drawComplexControl(control, option, painter, widget) + if control == CC_SLIDER and option.subControls & SC_HANDLE: + rect = self.subControlRect(control, option, SC_HANDLE, widget) + size = max(rect.width(), rect.height()) * 3 // 2 + painter.fillRect(rect.adjusted(-size, 0, size, 0), QColor(0, 0, 0, 20)) + + +@pytest.mark.skipif(not _PAGES_WITH_EACH_HANDLE, reason="Qt draws no pages with them") +@pytest.mark.parametrize( + "sheet, pages", + [ + (None, (False, False)), # (the glow, which moves with the handle) + (PAGES, (True, True)), + ( # (without a groove or handle rule, Qt leaves it all to the base style) + "QSlider::groove:horizontal { height: 6px; background: gray; }" + "QSlider::sub-page:horizontal { background: #00ff00; }", + (True, False), + ), + ], +) +def test_pages_drawn_with_handles( + qtbot: QtBot, sheet: str | None, pages: tuple[bool, bool] +) -> None: + slider = QRangeSlider(H) + qtbot.addWidget(slider) + style = _Glow("Fusion") # (the widget doesn't own it) + slider.setStyle(style) + if sheet: + slider.setStyleSheet(sheet) + slider.resize(200, 30) + image = QImage(slider.size(), QImage.Format.Format_ARGB32) + painter = QPainter(image) + try: + assert slider._pagesWithHandles(painter, slider._styleOption) == pages + finally: + painter.end() + + +def test_round_handles_show_the_bar_and_groove_around_them(qtbot: QtBot) -> None: + # (up to Qt 6.10.0, Qt draws style sheets' sub-page with each handle, in its rect) + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet( + "QSlider::groove:horizontal { height: 20px; background: #808080;" + " border-radius: 10px; }" + "QSlider::handle:horizontal { width: 20px; background: white;" + " border-radius: 10px; }" + "QSlider::sub-page:horizontal { background: #ff0000; }" + "QRangeSlider { qproperty-barColor: #0000ff; }" + ) + slider.resize(200, 30) + slider.setValue((30, 70)) + image = slider.grab().toImage() + ratio = image.width() / slider.width() + + def color(point: QPoint) -> QColor: + return image.pixelColor(round(point.x() * ratio), round(point.y() * ratio)) + + # (corners outside the circles) + first, last = slider._handleRect(0), slider._handleRect(1) + assert color(first.topLeft() + QPoint(1, 1)) == QColor("#808080") + assert color(first.topRight() + QPoint(-1, 1)) == QColor("#0000ff") + assert color(last.topLeft() + QPoint(1, 1)) == QColor("#0000ff") + assert color(last.topRight() + QPoint(-1, 1)) == QColor("#808080") + + +def test_bar_color_in_inactive_windows_on_windows(qtbot: QtBot) -> None: + # (Qt's Windows palettes have the accent in the window's color, when inactive) + slider = QRangeSlider(H) + qtbot.addWidget(slider) + style = QStyleFactory.create("Windows") # (which doesn't fill the groove) + slider.setStyle(style) + palette = slider.palette() + window = palette.color(QPalette.ColorRole.Window) + for role in ("Highlight", "Accent"): # (`Accent` is new in Qt 6.6) + if hasattr(QPalette.ColorRole, role): + palette.setColor(getattr(QPalette.ColorRole, role), window) + slider.setPalette(palette) + slider.resize(200, 30) + slider.setValue((30, 70)) + assert _bar_center(slider) != window + + +def _before_first_handle(slider: QRangeSlider) -> list[QColor]: + """The colors on the groove's center line, from the start to the first handle.""" + image = slider.grab().toImage() + ratio = image.width() / slider.width() + groove = slider.style().subControlRect( + CC_SLIDER, slider._styleOption, SC_GROOVE, slider + ) + handles = [slider._handleRect(i) for i in range(len(slider.value()))] + if slider.orientation() == H: + end = min(r.left() for r in handles) + points = [(x, groove.center().y()) for x in range(end)] + else: + end = min(r.top() for r in handles) + points = [(groove.center().x(), y) for y in range(end)] + return [image.pixelColor(round(x * ratio), round(y * ratio)) for x, y in points] + + +def _after_last_handle(slider: QRangeSlider) -> list[QColor]: + """The colors on the groove's center line, from the last handle to the end.""" + image = slider.grab().toImage() + ratio = image.width() / slider.width() + groove = slider.style().subControlRect( + CC_SLIDER, slider._styleOption, SC_GROOVE, slider + ) + handles = [slider._handleRect(i) for i in range(len(slider.value()))] + if slider.orientation() == H: + start = max(r.right() for r in handles) + 1 + points = [(x, groove.center().y()) for x in range(start, slider.width())] + else: + start = max(r.bottom() for r in handles) + 1 + points = [(groove.center().x(), y) for y in range(start, slider.height())] + return [image.pixelColor(round(x * ratio), round(y * ratio)) for x, y in points] + + +def _bar_center(slider: QRangeSlider) -> QColor: + """The color in the middle of the bar, on the groove's center line.""" + image = slider.grab().toImage() + ratio = image.width() / slider.width() + centers = [slider._handleRect(i).center() for i in (0, -1)] + groove = slider.style().subControlRect( + QStyle.ComplexControl.CC_Slider, + slider._styleOption, + QStyle.SubControl.SC_SliderGroove, + slider, + ) + x, y = (centers[0].x() + centers[1].x()) / 2, groove.center().y() + if slider.orientation() == V: + x, y = groove.center().x(), (centers[0].y() + centers[1].y()) / 2 + return image.pixelColor(round(x * ratio), round(y * ratio)) + + +@pytest.mark.parametrize("style", QStyleFactory.keys()) +@pytest.mark.parametrize("orientation", [H, V]) +@pytest.mark.parametrize("ticks", TICKS) +def test_bar_color_is_drawn_as_is( + qtbot: QtBot, style: str, orientation: Qt.Orientation, ticks: QSlider.TickPosition +) -> None: + slider = QRangeSlider(orientation) + qtbot.addWidget(slider) + qstyle = QStyleFactory.create(style) # (the widget doesn't own it) + slider.setStyle(qstyle) + slider.setTickPosition(ticks) + slider.resize(200, 30) if orientation == H else slider.resize(30, 200) + slider.setValue((30, 70)) + slider.barColor = "#ff0000" + assert _bar_center(slider) == QColor("#ff0000") + slider.barColor = "rgba(0, 0, 255, 255)" + assert _bar_center(slider) == QColor("#0000ff") + + +def test_translucent_bar_color(qtbot: QtBot) -> None: + # (like ndv's: a translucent groove and sub-page, and a translucent bar color) + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet( + "QSlider::groove:horizontal { height: 10px; background: rgba(0, 0, 0, 25); }" + "QSlider::sub-page:horizontal { background: rgba(0, 0, 0, 25); }" + "QRangeSlider { qproperty-barColor: rgba(255, 0, 0, 128); }" + ) + slider.resize(200, 30) + slider.setValue((30, 70)) + color = _bar_center(slider) + assert color.red() - color.green() > 100, color.name() # (half red, at least) + + +@pytest.mark.parametrize("cls", [QRangeSlider, QLabeledRangeSlider]) +def test_bar_color(qtbot: QtBot, cls: type) -> None: + slider = cls(H) + qtbot.addWidget(slider) + assert isinstance(slider.barColor, QBrush) # (the default: the style's) + + slider.barColor = "red" + assert slider.barColor.color() == QColor("red") + slider.barColor = QColor("blue") + assert slider.barColor.color() == QColor("blue") + slider.barColor = QBrush(QColor("green")) + assert slider.barColor.color() == QColor("green") + slider.barColor = "rgba(10, 20, 30, 40)" + assert slider.barColor.color() == QColor(10, 20, 30, 40) + slider.barColor = "qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 red, stop:1 blue)" + gradient = slider.barColor.gradient() + assert gradient is not None and gradient.type() == QGradient.Type.LinearGradient + slider.barColor = None + assert isinstance(slider.barColor, QBrush) + + +def test_bar_color_from_style_sheet(qtbot: QtBot) -> None: + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet("QRangeSlider { qproperty-barColor: #ff8800; }") + slider.ensurePolished() + assert slider.barColor.color() == QColor("#ff8800") + + +def test_bar_colors_by_state(qtbot: QtBot) -> None: + # (the slider's `_style` attributes, which some projects set directly) + slider = QLabeledDoubleRangeSlider(H) + qtbot.addWidget(slider) + slider._slider._style.brush_active = "red" + assert slider.barColor.color() == QColor("red") From ee1bdb8830b2310b173b11e9127e515d188d93c3 Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Sun, 15 Nov 2026 07:51:47 +0100 Subject: [PATCH 2/5] fix: range bar review fixes, and cache what's drawn but the handles From a review of the range slider's bar: - Don't crash rendering a slider too small (or scaled down too far) for images of it: draw nothing then. - Decide whether the style fills the groove once, in the middle of the groove between handles at its ends, not where the bar is: near an end, the groove there (from the slider drawn upside down) could differ from the filled one without a fill, as on macOS with ticks, and the bar was lost. - Draw the filled groove in place of the groove, not over it, so a translucent groove isn't drawn twice (as in macOS's inactive fill). - Leave out a style sheet's background, which Qt draws all over the slider each time, from the groove's bounds (the bar was as thick as the slider), and from what's drawn with handles. - Tell pages drawn with handles by an end that stays put as the handle moves (macOS draws its handle with ticks on both sides wider than its rect, and not centered on it, which looked like pages). What the style draws for the slider but its handles doesn't depend on where the handles are: it's now kept until the slider's state changes, or it's restyled, instead of being drawn off screen several times for each paint (as Qt's styles cache pixmaps of slider parts). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EHun8dgfLmXi4bkSHYqdKR --- src/superqt/sliders/_generic_range_slider.py | 389 ++++++++++++------- tests/zz_test_sliders/test_range_bar.py | 209 +++++++++- 2 files changed, 453 insertions(+), 145 deletions(-) diff --git a/src/superqt/sliders/_generic_range_slider.py b/src/superqt/sliders/_generic_range_slider.py index 3810863a..816e51f3 100644 --- a/src/superqt/sliders/_generic_range_slider.py +++ b/src/superqt/sliders/_generic_range_slider.py @@ -1,11 +1,13 @@ +from __future__ import annotations + import re -from collections.abc import Sequence from dataclasses import dataclass -from typing import Any, TypeVar +from typing import TYPE_CHECKING, Any, TypeVar from qtpy import QtGui from qtpy.QtCore import ( Property, + QEvent, QPoint, QPointF, QRect, @@ -24,6 +26,7 @@ QPainter, QPalette, QRadialGradient, + QTransform, ) from qtpy.QtWidgets import ( QApplication, @@ -43,14 +46,20 @@ _GenericSlider, ) +if TYPE_CHECKING: + from collections.abc import Sequence + _T = TypeVar("_T") SC_BAR = QStyle.SubControl.SC_ScrollBarSubPage +_QT = tuple(int(n) for n in re.findall(r"\d+", qVersion())[:3]) # whether Qt draws style sheets' sub-page and add-page with each handle (and so over # the bar), as it did up to 6.10.0 (https://bugreports.qt.io/browse/QTBUG-141157) -_QT = tuple(int(n) for n in re.findall(r"\d+", qVersion())[:3]) _PAGES_WITH_EACH_HANDLE = _QT < (6, 10, 1) +# whether styles may fill vertical grooves from the bottom whichever way the slider +# goes, as Windows 11 did up to 6.10.0 (see `_barOption`) +_FILLS_UP_EITHER_WAY = _QT < (6, 10, 1) class _GenericRangeSlider(_GenericSlider): @@ -77,6 +86,7 @@ class _GenericRangeSlider(_GenericSlider): def __init__(self, *args, **kwargs): self._style = _BarColors() self._macpatch = False # (whether `applyMacStylePatch` was called) + self._parts: _Parts | None = None # (see `_partsFor`) super().__init__(*args, **kwargs) @@ -98,8 +108,6 @@ def __init__(self, *args, **kwargs): self._bar_moves_all = True self._should_draw_bar = True - # color - self.setStyleSheet("") def _rename_signals(self) -> None: @@ -215,6 +223,11 @@ def _patch_style(self, style: str): style = MONTEREY_SLIDER_STYLES_FIX return style + def event(self, ev: QEvent) -> bool: + if ev.type() in _RESTYLED: + self._parts = None + return super().event(ev) + def mouseMoveEvent(self, ev: QtGui.QMouseEvent) -> None: if self._pressedControl == SC_BAR: ev.accept() @@ -231,12 +244,10 @@ def _event_position(self, event): def paintEvent(self, ev: QtGui.QPaintEvent) -> None: painter = QStylePainter(self) + if (self.size() * _ratio(painter)).isEmpty(): # (too small to draw anything) + return opt = self._styleOption - - bar = self._barOption(opt, _ratio(painter)) - groove = self._drawGroove(painter, bar) - if self._should_draw_bar: - self._drawBar(painter, opt, bar, groove) + self._drawBar(painter, opt) self._drawTicks(painter, opt) # (after the bar, which could cover them) self._draw_handle(painter, opt) @@ -305,33 +316,28 @@ def _handleRect( # Painting - def _drawGroove(self, painter: QStylePainter, bar: QStyleOptionSlider) -> QImage: - """Draw the style's groove, without any fill; return it. + def _partsFor(self, opt: QStyleOptionSlider, ratio: float) -> _Parts: + """What the style draws for the slider but its handles, in `opt`'s state. - (As the bar is drawn, by `bar`: see `_barOption`.) Styles fill the groove - from the minimum up to the handle, and some do even with the handle at the - minimum (e.g. Windows 11). Drawn upside down, that bit of fill is at the - other end: so the groove under a handle at the minimum comes from the slider - drawn upside down. But some styles fill from the same end either way: - Windows 11 up to Qt 6.10.0, and style sheets, whose sub-page is always at the - left or top, once Qt draws it with the groove - (https://bugreports.qt.io/browse/QTBUG-141608). Then that part of the groove - is the mirror image of its other end, in the colors next to it. + (At the painter's pixel ratio, `ratio`.) It's kept until the state changes, + or the style may draw the slider differently (see `_RESTYLED`), as the style + draws each part off screen, often more than once. """ + # (and the name, which style sheets' selectors may use) + key = (*_key(opt, ratio), self.objectName()) + if self._parts is not None and self._parts.key == key: + return self._parts + bar = self._barOption(opt, ratio) horizontal = bar.orientation == Qt.Orientation.Horizontal - ratio = _ratio(painter) - groove = self._grooveImage(bar, bar.minimum, ratio) - flipped = QStyleOptionSlider(bar) - flipped.upsideDown = not bar.upsideDown - other = self._grooveImage(flipped, bar.minimum, ratio) - option = QStyleOptionSlider(bar) + option.subControls = SC_NONE + background = self._sliderImage(option, ratio) # (e.g. a style sheet's) option.sliderPosition = option.minimum start = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) option.sliderPosition = option.maximum end = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) # (from the slider's end with the minimum to the far side of a handle at the - # minimum; and the groove between that and the other) + # minimum; and the slider between that and a handle at the maximum) under, between = QRect(self.rect()), QRect(self.rect()) if horizontal: under.setRight(start.right()) @@ -345,6 +351,43 @@ def _drawGroove(self, painter: QStylePainter, bar: QStyleOptionSlider) -> QImage under.setBottom(start.bottom()) between.setTop(start.bottom() + 1) between.setBottom(end.top() - 1) + groove = self._groove(bar, ratio, under, between) + # (with the handle: up to 6.12.0, style sheets only draw pages with one) + filled = self._grooveImage(bar, bar.maximum, ratio, handle=True) + # (in the middle: away from the ends, and from what handles there draw) + middle = QRect(between) + if horizontal: + middle.adjust(between.width() // 4, 0, -(between.width() // 4), 0) + else: + middle.adjust(0, between.height() // 4, 0, -(between.height() // 4)) + fills = _crop(filled, middle) != _crop(groove, middle) + pages = self._pagesWithHandles(opt, ratio, background) + self._parts = _Parts( + key, ratio, bar, background, groove, end, between, filled, fills, pages + ) + return self._parts + + def _groove( + self, bar: QStyleOptionSlider, ratio: float, under: QRect, between: QRect + ) -> QImage: + """The style's groove, without any fill. + + (As the bar is drawn, by `bar`: see `_barOption`.) Styles fill the groove + from the minimum up to the handle, and some do even with the handle at the + minimum (e.g. Windows 11). Drawn upside down, that bit of fill is at the + other end: so the groove under a handle at the minimum (`under`) comes from + the slider drawn upside down. But some styles fill from the same end either + way: Windows 11 up to Qt 6.10.0, and style sheets, whose sub-page is always + at the left or top, once Qt draws it with the groove + (https://bugreports.qt.io/browse/QTBUG-141608). Then, unless the groove is + the same either way (`between` the handles at both ends), that part of the + groove is the mirror image of its other end, in the colors next to it. + """ + horizontal = bar.orientation == Qt.Orientation.Horizontal + groove = self._grooveImage(bar, bar.minimum, ratio) + flipped = QStyleOptionSlider(bar) + flipped.upsideDown = not bar.upsideDown + other = self._grooveImage(flipped, bar.minimum, ratio) mix = QPainter(groove) mix.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) @@ -371,60 +414,53 @@ def _drawGroove(self, painter: QStylePainter, bar: QStyleOptionSlider) -> QImage mix.setCompositionMode(QPainter.CompositionMode.CompositionMode_SourceAtop) mix.drawImage(QRectF(under), mirror, next_to) mix.end() - painter.drawImage(0, 0, groove) return groove - def _drawBar( - self, - painter: QStylePainter, - opt: QStyleOptionSlider, - bar: QStyleOptionSlider, - groove: QImage, - ) -> None: - """Draw the bar between the outer handles, in the style's groove (`groove`). - - Without a `barColor`, it's the style's own fill of the groove, if it has one - (as on macOS, with Fusion and Windows 11, or a style sheet's sub-page): what - the slider drawn as the bar (`bar`, see `_barOption`) fills, up to the - handle, whichever way this one goes. Otherwise, it's a solid bar as thick as - the groove (and its fill), in the `barColor` (as is, in any state, like a - style sheet's colors) or the style's fill color. + def _drawBar(self, painter: QStylePainter, opt: QStyleOptionSlider) -> None: + """Draw the style's groove, with the bar between the outer handles. + + Without a `barColor`, the bar is the style's own fill of the groove, if it + has one (as on macOS, with Fusion and Windows 11, or a style sheet's + sub-page): the groove filled all along, in place of the groove between the + handles. Otherwise, it's a solid bar over the groove, as thick as the groove + (and its fill), in the `barColor` (as is, like a style sheet's colors) or + the style's fill color. """ + parts = self._partsFor(opt, _ratio(painter)) horizontal = opt.orientation == Qt.Orientation.Horizontal - ends = [self._handleRect(i, opt).center() for i in (0, -1)] - span = QRect(self.rect()) # (the part of the slider between the outer handles) - if horizontal: - span.setLeft(min(p.x() for p in ends)) - span.setRight(max(p.x() for p in ends)) - else: - span.setTop(min(p.y() for p in ends)) - span.setBottom(max(p.y() for p in ends)) - - # The groove, filled all along (as the bar is drawn), with a handle: up to - # 6.12.0, style sheets only draw pages with one. That handle, at the - # maximum, isn't part of the bar. - option = QStyleOptionSlider(bar) - option.sliderPosition = option.maximum - handle = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) - inner = _apart(span, handle, horizontal) - if inner.isEmpty(): # (the bar is under the handles) + span, inner = QRect(), QRect() + if self._should_draw_bar: + ends = [self._handleRect(i, opt).center() for i in (0, -1)] + span = QRect(self.rect()) # (the part between the outer handles) + if horizontal: + span.setLeft(min(p.x() for p in ends)) + span.setRight(max(p.x() for p in ends)) + else: + span.setTop(min(p.y() for p in ends)) + span.setBottom(max(p.y() for p in ends)) + # (the filled groove's handle, at the maximum, isn't part of the bar) + inner = _apart(span, parts.end, horizontal) + brush = self._barBrush(opt) + if inner.isEmpty() or brush is not None or not parts.fills: + painter.drawImage(0, 0, parts.groove) + else: # (in place of the groove, which it has too: it may be translucent) + groove = QImage(parts.groove) + mix = QPainter(groove) + mix.setCompositionMode(QPainter.CompositionMode.CompositionMode_Source) + mix.drawImage(inner.topLeft(), _crop(parts.filled, inner)) + mix.end() + painter.drawImage(0, 0, groove) return - empty = _crop(groove, inner) - ratio = _ratio(painter) - if (brush := self._barBrush(opt)) is None: - filled = self._grooveImage(option, option.maximum, ratio, handle=True) - filled = _crop(filled, inner) - if filled != empty: - painter.drawImage(inner.topLeft(), filled) - return - bounds = _bounds(empty) - else: # (filled without the handle, which may reach past its rect) - filled = self._grooveImage(option, option.maximum, ratio) - bounds = _bounds(_crop(filled, inner)) + if inner.isEmpty(): # (no bar, or it's under the handles) + return + if brush is None: + if parts.fill is None: + parts.fill = self._fillBrush(opt) + brush = parts.fill + bounds = self._grooveBounds(parts) if bounds.isEmpty(): # (the style draws no groove) - painter.fillRect(self._plainBar(opt, span), brush or self._fillBrush(opt)) + painter.fillRect(self._plainBar(opt, span), brush) else: # (even if the groove is hollow, or its fill translucent) - bounds.translate(QPointF(inner.topLeft())) rect = QRectF(span) if horizontal: rect.setTop(bounds.top()) @@ -432,7 +468,17 @@ def _drawBar( else: rect.setLeft(bounds.left()) rect.setRight(bounds.right()) - painter.fillRect(rect, brush or self._fillBrush(opt)) + painter.fillRect(rect, brush) + + def _grooveBounds(self, parts: _Parts) -> QRectF: + """Where the style draws the groove, filled all along, between the ends.""" + if parts.bounds is None: + bar, between = parts.bar, parts.between + # (without the handle, which may reach past its rect) + filled = self._grooveImage(bar, bar.maximum, parts.ratio) + bounds = _bounds(_crop(filled, between), _crop(parts.background, between)) + parts.bounds = bounds.translated(QPointF(between.topLeft())) + return parts.bounds def _barOption(self, opt: QStyleOptionSlider, ratio: float) -> QStyleOptionSlider: """A copy of `opt`, as the bar is drawn: with the minimum at the left, or top. @@ -444,7 +490,7 @@ def _barOption(self, opt: QStyleOptionSlider, ratio: float) -> QStyleOptionSlide """ option = QStyleOptionSlider(opt) option.upsideDown = False - if not _PAGES_WITH_EACH_HANDLE or opt.orientation == Qt.Orientation.Horizontal: + if not _FILLS_UP_EITHER_WAY or opt.orientation == Qt.Orientation.Horizontal: return option # (Style sheets then draw no pages with the groove alone: if, between handles # at both ends, it's not the same either way, its fill is by position.) @@ -496,17 +542,26 @@ def _grooveImage( return self._sliderImage(option, ratio, style) def _sliderImage( - self, opt: QStyleOptionSlider, ratio: float, style: QStyle | None = None + self, + opt: QStyleOptionSlider, + ratio: float, + style: QStyle | None = None, + transform: QTransform | None = None, ) -> QImage: """What the style draws for `opt`, as an image of the whole slider. (Of the whole slider: the macOS style mirrors inverted sliders around the - slider's rect, and ignores clipping.) `ratio` is the image's pixel ratio. + slider's rect, and ignores clipping.) `ratio` is the image's pixel ratio. A + null image if it would be empty (or too big to make). """ image = QImage(self.size() * ratio, QImage.Format.Format_ARGB32_Premultiplied) + if image.isNull(): + return image image.setDevicePixelRatio(ratio) image.fill(Qt.GlobalColor.transparent) painter = QPainter(image) + if transform is not None: + painter.setTransform(transform) (style or self.style()).drawComplexControl(CC_SLIDER, opt, painter, self) painter.end() return image @@ -517,8 +572,9 @@ def _fillBrush(self, opt: QStyleOptionSlider) -> QBrush: (The palette's accent, grayed if disabled or if it's the window's color.) It's read from a groove that the style draws without tick marks (with them, - macOS doesn't fill it), filled up to its maximum. (Not the style sheet's style, - which may not fill it: the app's, unless the slider has its own.) + macOS doesn't fill it), filled up to its maximum, by the app's style, unless + the slider has its own: e.g. not the style made for a style sheet on the + slider or its parents, which only fills it with a sub-page. """ style = self.style() if not self.testAttribute(Qt.WidgetAttribute.WA_SetStyle): @@ -528,7 +584,9 @@ def _fillBrush(self, opt: QStyleOptionSlider) -> QBrush: ratio = self.devicePixelRatioF() # (any: it's only for its color) empty = self._grooveImage(option, option.minimum, ratio, style) full = self._grooveImage(option, option.maximum, ratio, style) - center = _bounds(full).center() * ratio + option.subControls = SC_NONE + background = self._sliderImage(option, ratio, style) + center = _bounds(full, background).center() * ratio x, y = int(center.x()), int(center.y()) if full.valid(x, y) and full.pixel(x, y) != empty.pixel(x, y): return QBrush(full.pixelColor(x, y)) @@ -566,7 +624,7 @@ def _draw_handle(self, painter: QStylePainter, opt: QStyleOptionSlider): first = (max if opt.upsideDown else min)( range(len(positions)), key=positions.__getitem__ ) - pages = self._pagesWithHandles(painter, opt) + pages = self._partsFor(opt, _ratio(painter)).pages for idx, pos in enumerate(positions): opt.sliderPosition = pos # make pressed handles appear sunken @@ -578,41 +636,41 @@ def _draw_handle(self, painter: QStylePainter, opt: QStyleOptionSlider): self._drawHandle(painter, opt, pages, first=idx == first) def _pagesWithHandles( - self, painter: QStylePainter, opt: QStyleOptionSlider + self, + opt: QStyleOptionSlider, + ratio: float, + background: QImage | None = None, ) -> tuple[bool, bool]: """Whether the style draws a page before each handle, and one after it. (Style sheets' sub-page and add-page, which Qt draws with each handle up to 6.10.0: https://bugreports.qt.io/browse/QTBUG-141157.) With a handle at two places, off screen: a page runs from an end of the groove to the handle, so - it grows or shrinks as the handle moves, while a handle, and its shadow or - glow (however far it reaches), moves with it. + that end of what's drawn stays put as the handle moves, while a handle, and + its shadow or glow, moves with it. (`background`: what the style draws with + no sub-controls, e.g. a style sheet's background, which is neither.) """ if not _PAGES_WITH_EACH_HANDLE: return False, False - ratio = _ratio(painter) - quarter = (opt.maximum - opt.minimum) // 4 - one = self._pastHandle(opt, opt.minimum + quarter, ratio) - other = self._pastHandle(opt, opt.maximum - quarter, ratio) - return abs(one[0] - other[0]) > 1, abs(one[1] - other[1]) > 1 - - def _pastHandle( - self, opt: QStyleOptionSlider, position: int, ratio: float - ) -> tuple[float, float]: - """How far what the style draws for a handle at `position` reaches past it. - - (Before it, and after it: at its left and right, or top and bottom.) - """ + horizontal = opt.orientation == Qt.Orientation.Horizontal option = QStyleOptionSlider(opt) option.subControls = SC_HANDLE - option.sliderPosition = position - drawn = _bounds(self._sliderImage(option, ratio)) - if drawn.isEmpty(): - return 0.0, 0.0 - rect = QRectF(self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self)) - if opt.orientation == Qt.Orientation.Horizontal: - return rect.left() - drawn.left(), drawn.right() - rect.right() - return rect.top() - drawn.top(), drawn.bottom() - rect.bottom() + quarter = (opt.maximum - opt.minimum) // 4 + starts, ends = [], [] # (of the handle, and of what's drawn with it) + for position in (opt.minimum + quarter, opt.maximum - quarter): + option.sliderPosition = position + rect = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) + drawn = _bounds(self._sliderImage(option, ratio), background) + if drawn.isEmpty(): + return False, False + starts.append(rect.left() if horizontal else rect.top()) + if horizontal: + ends.append((drawn.left(), drawn.right())) + else: + ends.append((drawn.top(), drawn.bottom())) + if abs(starts[0] - starts[1]) <= 1: # (it hardly moved: too short to tell) + return False, False + return abs(ends[0][0] - ends[1][0]) <= 1, abs(ends[0][1] - ends[1][1]) <= 1 def _drawHandle( self, @@ -656,19 +714,14 @@ def _mirroredHandle( option = QStyleOptionSlider(opt) option.upsideDown = not opt.upsideDown there = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) - image = QImage(self.size() * ratio, QImage.Format.Format_ARGB32_Premultiplied) - image.setDevicePixelRatio(ratio) - image.fill(Qt.GlobalColor.transparent) - painter = QPainter(image) + transform = QTransform() if opt.orientation == Qt.Orientation.Horizontal: - painter.translate(rect.x() + there.x() + rect.width(), 0) - painter.scale(-1, 1) + transform.translate(rect.x() + there.x() + rect.width(), 0) + transform.scale(-1, 1) else: - painter.translate(0, rect.y() + there.y() + rect.height()) - painter.scale(1, -1) - self.style().drawComplexControl(CC_SLIDER, option, painter, self) - painter.end() - return image + transform.translate(0, rect.y() + there.y() + rect.height()) + transform.scale(1, -1) + return self._sliderImage(option, ratio, transform=transform) def _updateHoverControl(self, pos): old_hover = self._hoverControl, self._hoverIndex @@ -743,8 +796,9 @@ def _spreadAllPositions(self, shrink=False, gain=1.1, ref=None) -> None: class _BarColors: """Custom colors of the bar, for each state (`None`: the style's own). - `barColor` sets `brush_active`, which is also used for inactive windows. (It's the - slider's `_style`, whose attributes some projects set directly.) + `barColor` sets `brush_active`, which is also used for inactive windows, and for + disabled sliders with a style sheet. (It's the slider's `_style`, whose attributes + some projects set directly.) """ brush_active: Any = None @@ -752,6 +806,56 @@ class _BarColors: brush_disabled: Any = None +@dataclass +class _Parts: + """What the style draws for a range slider but its handles (see `_partsFor`).""" + + key: tuple # (what it depends on: see `_key`) + ratio: float # (the images' pixel ratio) + bar: QStyleOptionSlider # (the slider as the bar is drawn: see `_barOption`) + background: QImage # (what the style draws with no sub-controls) + groove: QImage # (without any fill: see `_groove`) + end: QRect # (a handle at the maximum, in `bar`) + between: QRect # (the slider between handles at its ends) + filled: QImage # (the groove filled all along, with that handle) + fills: bool # (whether the style fills the groove) + pages: tuple[bool, bool] # (see `_pagesWithHandles`) + bounds: QRectF | None = None # (see `_grooveBounds`) + fill: QBrush | None = None # (see `_fillBrush`) + + +# events after which the style may draw the slider differently +_RESTYLED = { + QEvent.Type.StyleChange, # (also when a style sheet changes, or a parent's) + QEvent.Type.PaletteChange, + QEvent.Type.FontChange, + QEvent.Type.DynamicPropertyChange, # (which style sheets' selectors may use) + QEvent.Type.Polish, +} + + +def _key(opt: QStyleOptionSlider, ratio: float) -> tuple: + """What the style's drawing of `opt` depends on, but where the handles are. + + (As for the pixmaps that Qt's styles cache: see `QStyleHelper::uniqueName`.) + """ + return ( + ratio, + opt.rect.getRect(), # (values: with PySide, the rect is the option's own) + opt.state, + opt.direction, + opt.palette.cacheKey(), + opt.orientation, + opt.upsideDown, + opt.tickPosition, + opt.tickInterval, + opt.pageStep, + opt.singleStep, + opt.minimum, + opt.maximum, + ) + + def _ratio(painter: QPainter) -> float: """The scale of what the painter paints on (e.g. 2 for a 2x image). @@ -804,30 +908,45 @@ def _symmetric(image: QImage, rect: QRect, horizontal: bool) -> QImage: return out -def _bounds(image: QImage) -> QRectF: - """The bounds of the image's pixels that aren't transparent (in logical pixels). +def _bounds(image: QImage, background: QImage | None = None) -> QRectF: + """The bounds of the image's visible pixels, in logical pixels. - (Even faint ones: the macOS groove is a black overlay with an alpha of ~5%.) + (Even faint ones: the macOS groove is a black overlay with an alpha of ~5%.) With + a `background` (of the same size), of those that differ from it. """ - alpha = image.convertToFormat(QImage.Format.Format_Alpha8) - bits = alpha.constBits() - if hasattr(bits, "setsize"): # (PyQt) - bits.setsize(alpha.sizeInBytes()) - data, stride, width = bytes(bits), alpha.bytesPerLine(), alpha.width() - rows, left, right = [], width, -1 - for y in range(alpha.height()): - row = data[y * stride : y * stride + width] - if visible := row.lstrip(b"\0"): + if image.isNull(): + return QRectF() + data, stride, width = _pixels(image), image.bytesPerLine(), image.width() * 4 + base = None if background is None else _pixels(background) + rows, left, right = [], width, -1 # (in bytes: 4 per pixel) + for y in range(image.height()): + row = int.from_bytes(data[y * stride : y * stride + width], "big") + if base is not None: + row ^= int.from_bytes(base[y * stride : y * stride + width], "big") + if row: # (premultiplied: a pixel is zero if it's transparent) rows.append(y) - left = min(left, width - len(visible)) - right = max(right, len(row.rstrip(b"\0")) - 1) + left = min(left, width - (row.bit_length() + 7) // 8) + right = max(right, width - 1 - ((row & -row).bit_length() - 1) // 8) if not rows: return QRectF() ratio = image.devicePixelRatio() - pixels = QRectF(left, rows[0], right - left + 1, rows[-1] - rows[0] + 1) + pixels = QRectF( + left // 4, + rows[0], + right // 4 - left // 4 + 1, + rows[-1] - rows[0] + 1, + ) return QRectF(pixels.topLeft() / ratio, pixels.size() / ratio) +def _pixels(image: QImage) -> bytes: + """The image's data.""" + bits = image.constBits() + if hasattr(bits, "setsize"): # (PyQt) + bits.setsize(image.sizeInBytes()) + return bytes(bits) + + def _to_brush(color: Any) -> QBrush | None: """`color` as a brush: a QBrush, QColor, QGradient, or a string (see `_parse`).""" if color is None or isinstance(color, QBrush): diff --git a/tests/zz_test_sliders/test_range_bar.py b/tests/zz_test_sliders/test_range_bar.py index 596922ab..51940871 100644 --- a/tests/zz_test_sliders/test_range_bar.py +++ b/tests/zz_test_sliders/test_range_bar.py @@ -7,10 +7,13 @@ import pytest from qtpy.QtCore import QPoint, QRect, Qt from qtpy.QtGui import QBrush, QColor, QGradient, QImage, QPainter, QPalette -from qtpy.QtWidgets import QProxyStyle, QSlider, QStyle, QStyleFactory +from qtpy.QtWidgets import QProxyStyle, QSlider, QStyle, QStyleFactory, QWidget from superqt import QLabeledDoubleRangeSlider, QLabeledRangeSlider, QRangeSlider -from superqt.sliders._generic_range_slider import _PAGES_WITH_EACH_HANDLE +from superqt.sliders._generic_range_slider import ( + _FILLS_UP_EITHER_WAY, + _PAGES_WITH_EACH_HANDLE, +) from superqt.sliders._generic_slider import CC_SLIDER, SC_GROOVE, SC_HANDLE if TYPE_CHECKING: @@ -61,6 +64,44 @@ def test_bar_is_visible( assert _bar_visible(slider) +@pytest.mark.parametrize("style", QStyleFactory.keys()) +@pytest.mark.parametrize("orientation", [H, V]) +@pytest.mark.parametrize("ticks", TICKS) +@pytest.mark.parametrize("value", [(0, 99), (30, 99), (0, 70)]) +def test_bar_is_visible_with_handles_at_the_ends( + qtbot: QtBot, + style: str, + orientation: Qt.Orientation, + ticks: QSlider.TickPosition, + value: tuple[int, int], +) -> None: + slider = QRangeSlider(orientation) + qtbot.addWidget(slider) + qstyle = QStyleFactory.create(style) # (the widget doesn't own it) + slider.setStyle(qstyle) + slider.setTickPosition(ticks) + slider.resize(200, 30) if orientation == H else slider.resize(30, 200) + slider.setValue(value) + for inverted in (False, True): + slider.setInvertedAppearance(inverted) + with_bar = _bar_center_line(slider) + slider.hideBar() + assert _bar_center_line(slider) != with_bar + slider.showBar() + + +def _bar_center_line(slider: QRangeSlider) -> list[int]: + """The pixels across the slider in the middle of the bar.""" + image = slider.grab().toImage() + ratio = image.width() / slider.width() + centers = [slider._handleRect(i).center() for i in (0, -1)] + if slider.orientation() == H: + x = round((centers[0].x() + centers[1].x()) / 2 * ratio) + return [image.pixel(x, y) for y in range(image.height())] + y = round((centers[0].y() + centers[1].y()) / 2 * ratio) + return [image.pixel(x, y) for x in range(image.width())] + + def test_bar_with_style_sheet(qtbot: QtBot) -> None: slider = QRangeSlider(H) qtbot.addWidget(slider) @@ -149,9 +190,9 @@ def drawComplexControl(self, control, option, painter, widget=None) -> None: def test_no_fill_outside_the_bar( qtbot: QtBot, follows: bool, orientation: Qt.Orientation, inverted: bool ) -> None: - if not follows and orientation == V and not _PAGES_WITH_EACH_HANDLE: + if not follows and orientation == V and not _FILLS_UP_EITHER_WAY: # (then it's drawn like a style sheet: the bar is the part before a handle) - pytest.skip("only Windows 11 up to Qt 6.10.0 fills from the bottom either way") + pytest.skip("only up to Qt 6.10.0 (as Windows 11) is it filled up either way") slider = QRangeSlider(orientation) qtbot.addWidget(slider) style = _FillsFromMinimum(follows) # (the widget doesn't own it) @@ -181,6 +222,12 @@ def drawComplexControl(self, control, option, painter, widget=None) -> None: [ (None, (False, False)), # (the glow, which moves with the handle) (PAGES, (True, True)), + ( # (with a background, which Qt draws all over the slider each time) + "QRangeSlider { background: #303030; }" + "QSlider::groove:horizontal { height: 6px; background: gray; }" + "QSlider::add-page:horizontal { background: #0000ff; }", + (False, True), + ), ( # (without a groove or handle rule, Qt leaves it all to the base style) "QSlider::groove:horizontal { height: 6px; background: gray; }" "QSlider::sub-page:horizontal { background: #00ff00; }", @@ -198,12 +245,7 @@ def test_pages_drawn_with_handles( if sheet: slider.setStyleSheet(sheet) slider.resize(200, 30) - image = QImage(slider.size(), QImage.Format.Format_ARGB32) - painter = QPainter(image) - try: - assert slider._pagesWithHandles(painter, slider._styleOption) == pages - finally: - painter.end() + assert slider._partsFor(slider._styleOption, 1.0).pages == pages def test_round_handles_show_the_bar_and_groove_around_them(qtbot: QtBot) -> None: @@ -371,3 +413,150 @@ def test_bar_colors_by_state(qtbot: QtBot) -> None: qtbot.addWidget(slider) slider._slider._style.brush_active = "red" assert slider.barColor.color() == QColor("red") + + +def test_tiny_and_scaled_down(qtbot: QtBot) -> None: + # (too small for images of the slider) + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.resize(0, 0) + assert isinstance(slider.barColor, QBrush) + slider.resize(200, 30) + image = QImage(2, 1, QImage.Format.Format_ARGB32_Premultiplied) + painter = QPainter(image) + painter.scale(0.01, 0.01) + slider.render(painter, QPoint()) + painter.end() + + +def test_disabled_bar_from_the_style_sheet(qtbot: QtBot) -> None: + # (as a disabled QSlider's sub-page: a `barColor` is for enabled sliders) + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet( + "QSlider::groove:horizontal { height: 6px; background: gray; }" + "QSlider::sub-page:horizontal { background: seagreen; }" + "QSlider::sub-page:horizontal:disabled { background: #9a9a9a; }" + "QRangeSlider { qproperty-barColor: #ff8800; }" + ) + slider.resize(200, 30) + slider.setValue((30, 70)) + assert _bar_center(slider) == QColor("#ff8800") + slider.setEnabled(False) + assert _bar_center(slider) == QColor("#9a9a9a") + + +def test_bar_not_thicker_than_the_groove_with_a_background(qtbot: QtBot) -> None: + # (a style sheet's background, which Qt draws all over the slider each time) + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet( + "QRangeSlider { background: #303030; qproperty-barColor: #ff0000; }" + "QSlider::groove:horizontal { height: 6px; background: gray; }" + ) + slider.resize(200, 30) + slider.setValue((30, 70)) + image = slider.grab().toImage() + ratio = image.width() / slider.width() + groove = slider.style().subControlRect( + CC_SLIDER, slider._styleOption, SC_GROOVE, slider + ) + x = round(slider.width() / 2 * ratio) + above = image.pixelColor(x, round((groove.top() - 3) * ratio)) + assert above != QColor("#ff0000") + + +def test_translucent_sub_page_as_in_a_slider(qtbot: QtBot) -> None: + # (the bar is the groove filled, in place of the groove: not over it) + sheet = ( + "QSlider::groove:horizontal { height: 10px; background: rgba(0, 0, 0, 60); }" + "QSlider::handle:horizontal { width: 10px; background: white; }" + "QSlider::sub-page:horizontal { background: rgba(255, 0, 0, 60); }" + ) + parent = QWidget() + qtbot.addWidget(parent) + single, double = QSlider(H, parent), QRangeSlider(H, parent) + for slider, value in ((single, 80), (double, (20, 80))): + slider.setStyleSheet(sheet) + slider.resize(200, 30) + slider.setValue(value) + middle = single.rect().center() + image = single.grab().toImage() + ratio = image.width() / single.width() + expected = image.pixelColor(round(middle.x() * ratio), round(middle.y() * ratio)) + # (but for rounding, through an image, in older Qt: drawn over it, it's ~35 off) + pairs = zip(_bar_center(double).getRgb(), expected.getRgb(), strict=True) + assert max(abs(a - b) for a, b in pairs) <= 2 + + +SUB_PAGE = """ +QSlider::groove:horizontal {{ height: 6px; background: gray; }} +QSlider::sub-page:horizontal {{ background: {}; }} +""" + + +def _restyled_slider(qtbot: QtBot, parent: QWidget | None = None) -> QRangeSlider: + slider = QRangeSlider(H, parent) + if parent is None: + qtbot.addWidget(slider) + slider.resize(200, 30) + slider.setValue((30, 70)) + return slider + + +def test_restyled_by_its_style_sheet(qtbot: QtBot) -> None: + # (what's drawn of the slider but its handles is kept: until it's restyled) + slider = _restyled_slider(qtbot) + slider.setStyleSheet(SUB_PAGE.format("#00ff00")) + assert _bar_center(slider) == QColor("#00ff00") + slider.setStyleSheet(SUB_PAGE.format("#ff0000")) + assert _bar_center(slider) == QColor("#ff0000") + + +def test_restyled_by_its_parent_style_sheet(qtbot: QtBot) -> None: + parent = QWidget() + qtbot.addWidget(parent) + slider = _restyled_slider(qtbot, parent) + parent.setStyleSheet(SUB_PAGE.format("#00ff00")) + assert _bar_center(slider) == QColor("#00ff00") + parent.setStyleSheet(SUB_PAGE.format("#ff0000")) + assert _bar_center(slider) == QColor("#ff0000") + + +@pytest.mark.parametrize("selector", ['[hot="true"]', "#hot"]) +def test_restyled_when_repolished(qtbot: QtBot, selector: str) -> None: + slider = _restyled_slider(qtbot) + slider.setStyleSheet( + SUB_PAGE.format("#00ff00") + + f"QSlider{selector}::sub-page:horizontal {{ background: #ff0000; }}" + ) + assert _bar_center(slider) == QColor("#00ff00") + slider.setProperty("hot", True) + slider.setObjectName("hot") + slider.style().unpolish(slider) + slider.style().polish(slider) + assert _bar_center(slider) == QColor("#ff0000") + + +def test_restyled_by_its_palette(qtbot: QtBot) -> None: + slider = _restyled_slider(qtbot) + style = QStyleFactory.create("Fusion") # (the widget doesn't own it) + slider.setStyle(style) + before = _bar_center(slider) + palette = slider.palette() + for role in ("Highlight", "Accent"): # (`Accent` is new in Qt 6.6) + if hasattr(QPalette.ColorRole, role): + palette.setColor(getattr(QPalette.ColorRole, role), QColor("#ff00ff")) + slider.setPalette(palette) + assert _bar_center(slider) != before + + +def test_restyled_by_its_style(qtbot: QtBot) -> None: + slider = _restyled_slider(qtbot) + fusion = QStyleFactory.create("Fusion") # (the widget doesn't own it) + slider.setStyle(fusion) + slider.barColor = "#ff0000" + before = slider.grab().toImage() + windows = QStyleFactory.create("Windows") + slider.setStyle(windows) + assert slider.grab().toImage() != before From d7f4967281c8cb96f9b29a9b476849f094dd0bb9 Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Sun, 15 Nov 2026 22:52:12 +0100 Subject: [PATCH 3/5] fix: range bar review fixes: end gap, slivers, and keeping the cache - the bar is drawn from the groove filled without a handle, when the style fills it that way: no groove shows between it and a handle at the maximum (macOS's knob is smaller than its rect) - no bar between handles in one place (a 1px sliver showed through translucent ones) - no painting on a null image for style sheets without a handle rule (up to 6.10.0) - the cache is kept when the style sets properties on the slider as it paints it (Windows 11, for its animations), and dropped when the color scheme changes - one image fewer in the cache (the background is only drawn when needed) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EHun8dgfLmXi4bkSHYqdKR --- src/superqt/sliders/_generic_range_slider.py | 88 ++++++++----- tests/zz_test_sliders/test_range_bar.py | 130 ++++++++++++++++++- 2 files changed, 184 insertions(+), 34 deletions(-) diff --git a/src/superqt/sliders/_generic_range_slider.py b/src/superqt/sliders/_generic_range_slider.py index 816e51f3..f357fa41 100644 --- a/src/superqt/sliders/_generic_range_slider.py +++ b/src/superqt/sliders/_generic_range_slider.py @@ -21,6 +21,7 @@ QBrush, QColor, QGradient, + QGuiApplication, QImage, QLinearGradient, QPainter, @@ -87,6 +88,7 @@ def __init__(self, *args, **kwargs): self._style = _BarColors() self._macpatch = False # (whether `applyMacStylePatch` was called) self._parts: _Parts | None = None # (see `_partsFor`) + self._painting = False super().__init__(*args, **kwargs) @@ -224,7 +226,9 @@ def _patch_style(self, style: str): return style def event(self, ev: QEvent) -> bool: - if ev.type() in _RESTYLED: + # (not as it's painted: styles may set properties on the slider as they draw + # it, e.g. Windows 11, for its animations) + if ev.type() in _RESTYLED and not self._painting: self._parts = None return super().event(ev) @@ -247,9 +251,13 @@ def paintEvent(self, ev: QtGui.QPaintEvent) -> None: if (self.size() * _ratio(painter)).isEmpty(): # (too small to draw anything) return opt = self._styleOption - self._drawBar(painter, opt) - self._drawTicks(painter, opt) # (after the bar, which could cover them) - self._draw_handle(painter, opt) + self._painting = True + try: + self._drawBar(painter, opt) + self._drawTicks(painter, opt) # (after the bar, which could cover them) + self._draw_handle(painter, opt) + finally: + self._painting = False # ############### Implementation Details ####################### @@ -323,15 +331,14 @@ def _partsFor(self, opt: QStyleOptionSlider, ratio: float) -> _Parts: or the style may draw the slider differently (see `_RESTYLED`), as the style draws each part off screen, often more than once. """ - # (and the name, which style sheets' selectors may use) - key = (*_key(opt, ratio), self.objectName()) + # (and the name, which style sheets' selectors may use, and the color scheme, + # which styles may draw in, whatever the palette: e.g. on macOS) + key = (*_key(opt, ratio), self.objectName(), _colorScheme()) if self._parts is not None and self._parts.key == key: return self._parts bar = self._barOption(opt, ratio) horizontal = bar.orientation == Qt.Orientation.Horizontal option = QStyleOptionSlider(bar) - option.subControls = SC_NONE - background = self._sliderImage(option, ratio) # (e.g. a style sheet's) option.sliderPosition = option.minimum start = self.style().subControlRect(CC_SLIDER, option, SC_HANDLE, self) option.sliderPosition = option.maximum @@ -352,18 +359,22 @@ def _partsFor(self, opt: QStyleOptionSlider, ratio: float) -> _Parts: between.setTop(start.bottom() + 1) between.setBottom(end.top() - 1) groove = self._groove(bar, ratio, under, between) - # (with the handle: up to 6.12.0, style sheets only draw pages with one) - filled = self._grooveImage(bar, bar.maximum, ratio, handle=True) # (in the middle: away from the ends, and from what handles there draw) middle = QRect(between) if horizontal: middle.adjust(between.width() // 4, 0, -(between.width() // 4), 0) else: middle.adjust(0, between.height() // 4, 0, -(between.height() // 4)) + filled, drawn = self._grooveImage(bar, bar.maximum, ratio), QRect() fills = _crop(filled, middle) != _crop(groove, middle) - pages = self._pagesWithHandles(opt, ratio, background) + if not fills: # (up to 6.12.0, style sheets only draw pages with a handle) + handled = self._grooveImage(bar, bar.maximum, ratio, handle=True) + if _crop(handled, middle) != _crop(groove, middle): + # (with one at the maximum, which isn't part of the bar) + filled, drawn, fills = handled, end, True + pages = self._pagesWithHandles(opt, ratio) self._parts = _Parts( - key, ratio, bar, background, groove, end, between, filled, fills, pages + key, ratio, bar, groove, between, filled, drawn, fills, pages ) return self._parts @@ -429,17 +440,18 @@ def _drawBar(self, painter: QStylePainter, opt: QStyleOptionSlider) -> None: parts = self._partsFor(opt, _ratio(painter)) horizontal = opt.orientation == Qt.Orientation.Horizontal span, inner = QRect(), QRect() - if self._should_draw_bar: - ends = [self._handleRect(i, opt).center() for i in (0, -1)] + ends = [self._handleRect(i, opt).center() for i in (0, -1)] + start, stop = sorted(p.x() if horizontal else p.y() for p in ends) + if self._should_draw_bar and start < stop: span = QRect(self.rect()) # (the part between the outer handles) if horizontal: - span.setLeft(min(p.x() for p in ends)) - span.setRight(max(p.x() for p in ends)) + span.setLeft(start) + span.setRight(stop) else: - span.setTop(min(p.y() for p in ends)) - span.setBottom(max(p.y() for p in ends)) - # (the filled groove's handle, at the maximum, isn't part of the bar) - inner = _apart(span, parts.end, horizontal) + span.setTop(start) + span.setBottom(stop) + # (any handle drawn with the filled groove isn't part of the bar) + inner = _apart(span, parts.drawn, horizontal) brush = self._barBrush(opt) if inner.isEmpty() or brush is not None or not parts.fills: painter.drawImage(0, 0, parts.groove) @@ -473,10 +485,14 @@ def _drawBar(self, painter: QStylePainter, opt: QStyleOptionSlider) -> None: def _grooveBounds(self, parts: _Parts) -> QRectF: """Where the style draws the groove, filled all along, between the ends.""" if parts.bounds is None: - bar, between = parts.bar, parts.between - # (without the handle, which may reach past its rect) - filled = self._grooveImage(bar, bar.maximum, parts.ratio) - bounds = _bounds(_crop(filled, between), _crop(parts.background, between)) + bar, between, filled = parts.bar, parts.between, parts.filled + if not parts.drawn.isEmpty(): # (without the handle: it may reach past it) + filled = self._grooveImage(bar, bar.maximum, parts.ratio) + option = QStyleOptionSlider(bar) + option.subControls = SC_NONE + # (e.g. a style sheet's background, which is drawn all over the slider) + background = self._sliderImage(option, parts.ratio) + bounds = _bounds(_crop(filled, between), _crop(background, between)) parts.bounds = bounds.translated(QPointF(between.topLeft())) return parts.bounds @@ -636,10 +652,7 @@ def _draw_handle(self, painter: QStylePainter, opt: QStyleOptionSlider): self._drawHandle(painter, opt, pages, first=idx == first) def _pagesWithHandles( - self, - opt: QStyleOptionSlider, - ratio: float, - background: QImage | None = None, + self, opt: QStyleOptionSlider, ratio: float ) -> tuple[bool, bool]: """Whether the style draws a page before each handle, and one after it. @@ -647,13 +660,15 @@ def _pagesWithHandles( 6.10.0: https://bugreports.qt.io/browse/QTBUG-141157.) With a handle at two places, off screen: a page runs from an end of the groove to the handle, so that end of what's drawn stays put as the handle moves, while a handle, and - its shadow or glow, moves with it. (`background`: what the style draws with - no sub-controls, e.g. a style sheet's background, which is neither.) + its shadow or glow, moves with it. (Apart from what the style draws with no + sub-controls, e.g. a style sheet's background, which is neither.) """ if not _PAGES_WITH_EACH_HANDLE: return False, False horizontal = opt.orientation == Qt.Orientation.Horizontal option = QStyleOptionSlider(opt) + option.subControls = SC_NONE + background = self._sliderImage(option, ratio) option.subControls = SC_HANDLE quarter = (opt.maximum - opt.minimum) // 4 starts, ends = [], [] # (of the handle, and of what's drawn with it) @@ -693,6 +708,8 @@ def _drawHandle( if any(pages): # (style sheet handles, which don't blend with what's behind) ratio = _ratio(painter) rect = self.style().subControlRect(CC_SLIDER, opt, SC_HANDLE, self) + if rect.isEmpty(): # (e.g. a style sheet with no rule for it) + return if all(pages) and first: image = _crop(self._mirroredHandle(opt, rect, ratio), rect) else: @@ -813,11 +830,10 @@ class _Parts: key: tuple # (what it depends on: see `_key`) ratio: float # (the images' pixel ratio) bar: QStyleOptionSlider # (the slider as the bar is drawn: see `_barOption`) - background: QImage # (what the style draws with no sub-controls) groove: QImage # (without any fill: see `_groove`) - end: QRect # (a handle at the maximum, in `bar`) between: QRect # (the slider between handles at its ends) - filled: QImage # (the groove filled all along, with that handle) + filled: QImage # (the groove filled all along, maybe with a handle: see `drawn`) + drawn: QRect # (that handle, at the maximum, in `bar`: if any) fills: bool # (whether the style fills the groove) pages: tuple[bool, bool] # (see `_pagesWithHandles`) bounds: QRectF | None = None # (see `_grooveBounds`) @@ -856,6 +872,12 @@ def _key(opt: QStyleOptionSlider, ratio: float) -> tuple: ) +def _colorScheme() -> Any: + """The app's color scheme (in Qt 6.5+).""" + hints = QGuiApplication.styleHints() + return hints.colorScheme() if hasattr(hints, "colorScheme") else None + + def _ratio(painter: QPainter) -> float: """The scale of what the painter paints on (e.g. 2 for a 2x image). diff --git a/tests/zz_test_sliders/test_range_bar.py b/tests/zz_test_sliders/test_range_bar.py index 51940871..5a594dc1 100644 --- a/tests/zz_test_sliders/test_range_bar.py +++ b/tests/zz_test_sliders/test_range_bar.py @@ -6,7 +6,15 @@ import pytest from qtpy.QtCore import QPoint, QRect, Qt -from qtpy.QtGui import QBrush, QColor, QGradient, QImage, QPainter, QPalette +from qtpy.QtGui import ( + QBrush, + QColor, + QGradient, + QGuiApplication, + QImage, + QPainter, + QPalette, +) from qtpy.QtWidgets import QProxyStyle, QSlider, QStyle, QStyleFactory, QWidget from superqt import QLabeledDoubleRangeSlider, QLabeledRangeSlider, QRangeSlider @@ -102,6 +110,64 @@ def _bar_center_line(slider: QRangeSlider) -> list[int]: return [image.pixel(x, y) for x in range(image.width())] +@pytest.mark.parametrize("style", QStyleFactory.keys()) +@pytest.mark.parametrize("orientation", [H, V]) +@pytest.mark.parametrize("inverted", [False, True]) +def test_bar_reaches_a_handle_at_the_maximum( + qtbot: QtBot, style: str, orientation: Qt.Orientation, inverted: bool +) -> None: + # (no groove shows between them: e.g. by macOS's knob, which is smaller than its + # rect, as by a slider's at its maximum) + qstyle = QStyleFactory.create(style) # (the widgets don't own it) + slider, empty, full = (QRangeSlider(orientation), *map(QSlider, [orientation] * 2)) + for widget in (slider, empty, full): + qtbot.addWidget(widget) + widget.setStyle(qstyle) + widget.resize(200, 30) if orientation == H else widget.resize(30, 200) + widget.setInvertedAppearance(inverted) + widget.setRange(0, 99) + slider.setValue((30, 99)) + empty.setValue(0) + full.setValue(99) + images = [w.grab().toImage() for w in (slider, empty, full)] + ratio = images[0].width() / slider.width() + line = slider.style().subControlRect( + CC_SLIDER, slider._styleOption, SC_GROOVE, slider + ) + centers = [slider._handleRect(i).center() for i in (0, -1)] + if orientation == H: + middle, end = (centers[0].x() + centers[1].x()) / 2, centers[1].x() + else: + middle, end = (centers[0].y() + centers[1].y()) / 2, centers[1].y() + lo, hi = sorted((round(middle * ratio), round(end * ratio))) + for at in range(lo, hi + 1): + if orientation == H: + x, y = at, round(line.center().y() * ratio) + else: + x, y = round(line.center().x() * ratio), at + bar, groove, knob = (image.pixel(x, y) for image in images) + assert bar != groove or bar == knob, (x, y) + + +@pytest.mark.parametrize("value", [(50,), (50, 50)]) +def test_no_bar_between_handles_in_one_place( + qtbot: QtBot, value: tuple[int, ...] +) -> None: + # (which would show through a translucent handle) + slider = QRangeSlider(H) + qtbot.addWidget(slider) + slider.setStyleSheet( + "QSlider::groove:horizontal { height: 10px; background: gray; }" + "QSlider::handle:horizontal { width: 20px; background: rgba(0, 0, 255, 60); }" + ) + slider.barColor = "red" + slider.resize(200, 30) + slider.setValue(value) + with_bar = slider.grab().toImage() + slider.hideBar() + assert slider.grab().toImage() == with_bar + + def test_bar_with_style_sheet(qtbot: QtBot) -> None: slider = QRangeSlider(H) qtbot.addWidget(slider) @@ -429,6 +495,14 @@ def test_tiny_and_scaled_down(qtbot: QtBot) -> None: painter.end() +def test_style_sheet_without_a_handle(qtbot: QtBot, qtlog) -> None: + # (Qt then gives the handle an empty rect) + slider = _restyled_slider(qtbot) + slider.setStyleSheet(SUB_PAGE.format("#00ff00")) + slider.grab() + assert not [r.message for r in qtlog.records if "QPainter" in r.message] + + def test_disabled_bar_from_the_style_sheet(qtbot: QtBot) -> None: # (as a disabled QSlider's sub-page: a `barColor` is for enabled sliders) slider = QRangeSlider(H) @@ -560,3 +634,57 @@ def test_restyled_by_its_style(qtbot: QtBot) -> None: windows = QStyleFactory.create("Windows") slider.setStyle(windows) assert slider.grab().toImage() != before + + +class _Animated(QProxyStyle): + """A style that sets a property on what it draws (as Windows 11 does).""" + + def drawComplexControl(self, control, option, painter, widget=None) -> None: + if widget is not None: + widget.setProperty("_frame", (widget.property("_frame") or 0) + 1) + super().drawComplexControl(control, option, painter, widget) + + +def test_kept_while_the_style_sets_properties(qtbot: QtBot) -> None: + slider = _restyled_slider(qtbot) + style = _Animated("Fusion") # (the widget doesn't own it) + slider.setStyle(style) + slider.grab() + parts = slider._parts + slider.grab() + assert parts is not None + assert slider._parts is parts + + +class _Schemed(QProxyStyle): + """A style that draws the groove in a color by the app's color scheme.""" + + def drawComplexControl(self, control, option, painter, widget=None) -> None: + if option.subControls & SC_GROOVE: + dark = QGuiApplication.styleHints().colorScheme() == Qt.ColorScheme.Dark + painter.fillRect(option.rect, QColor("#ff0000" if dark else "#00ff00")) + + +def test_restyled_by_the_color_scheme(qtbot: QtBot) -> None: + # (even with a palette of its own, all of it, which the scheme doesn't change) + hints = QGuiApplication.styleHints() + if not hasattr(hints, "setColorScheme"): # (new in Qt 6.8) + pytest.skip("can't set the color scheme") + slider = _restyled_slider(qtbot) + style = _Schemed("Fusion") # (the widget doesn't own it) + slider.setStyle(style) + palette = QPalette() + for group in (QPalette.ColorGroup.Active, QPalette.ColorGroup.Inactive): + for role in QPalette.ColorRole: + if role not in (QPalette.ColorRole.NoRole, QPalette.ColorRole.NColorRoles): + palette.setColor(group, role, palette.color(group, role)) + slider.setPalette(palette) + try: + hints.setColorScheme(Qt.ColorScheme.Dark) + if hints.colorScheme() != Qt.ColorScheme.Dark: + pytest.skip("the platform doesn't set the color scheme") + before = _before_first_handle(slider) + hints.setColorScheme(Qt.ColorScheme.Light) + assert _before_first_handle(slider) != before + finally: + hints.unsetColorScheme() From bb0883f04aa5dfe63a192546f55c2dda5b962f7e Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Mon, 16 Nov 2026 08:48:48 +0100 Subject: [PATCH 4/5] fix: report a style sheet's sub-page as the range slider's barColor Without a custom color, `barColor` returns the color the style fills the groove with where it draws the bar (e.g. a style sheet's sub-page), as main did, rather than the app style's accent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EHun8dgfLmXi4bkSHYqdKR --- src/superqt/sliders/_generic_range_slider.py | 10 +++++++++- tests/zz_test_sliders/test_range_bar.py | 1 + 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/superqt/sliders/_generic_range_slider.py b/src/superqt/sliders/_generic_range_slider.py index f357fa41..007c3412 100644 --- a/src/superqt/sliders/_generic_range_slider.py +++ b/src/superqt/sliders/_generic_range_slider.py @@ -285,7 +285,15 @@ def _neighbor_bound(self, val, index): def _getBarColor(self) -> QBrush: opt = self._styleOption - return self._barBrush(opt) or self._fillBrush(opt) + if (brush := self._barBrush(opt)) is not None: + return brush + parts = self._partsFor(opt, self.devicePixelRatioF()) + if parts.fills: # (the color drawn: e.g. a style sheet's sub-page) + center = self._grooveBounds(parts).center() * parts.ratio + x, y = int(center.x()), int(center.y()) + if parts.filled.valid(x, y): + return QBrush(parts.filled.pixelColor(x, y)) + return self._fillBrush(opt) def _setBarColor(self, color: Any) -> None: self._style.brush_active = color diff --git a/tests/zz_test_sliders/test_range_bar.py b/tests/zz_test_sliders/test_range_bar.py index 5a594dc1..4b400cb2 100644 --- a/tests/zz_test_sliders/test_range_bar.py +++ b/tests/zz_test_sliders/test_range_bar.py @@ -193,6 +193,7 @@ def test_bar_from_style_sheet_sub_page(qtbot: QtBot) -> None: middle = slider.rect().center() color = image.pixelColor(round(middle.x() * ratio), round(middle.y() * ratio)) assert color == QColor("#00ff00") + assert slider.barColor.color() == QColor("#00ff00") PAGES = """ From ec58d1fb3fb9652da33a28cccaa6234f8ce21ee0 Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Tue, 17 Nov 2026 10:58:38 +0100 Subject: [PATCH 5/5] deprecate MONTEREY_SLIDER_STYLES_FIX --- docs/faq.md | 9 +-------- src/superqt/sliders/__init__.py | 19 +++++++++++++++++-- tests/zz_test_sliders/test_generic_slider.py | 7 +++++++ 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/docs/faq.md b/docs/faq.md index 0fd1edc0..eea807f2 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -12,15 +12,8 @@ Superqt includes a workaround for this issue, but it is not perfect, and it requires using a custom stylesheet (which may interfere with your own styles). Note that you may not see this issue if you're already using custom stylesheets. - To opt in to the workaround, do any of the following: + To opt in to the workaround, do either of the following: - set the environment variable `USE_MAC_SLIDER_PATCH=1` before importing superqt (note: this is safe to use even if you're targeting more than just MacOS 12, it will only be applied when needed) - call the `applyMacStylePatch()` method on any of the superqt slider subclasses (note, this will override your slider styles) - - apply the stylesheet manually: - - ```python - from superqt.sliders import MONTEREY_SLIDER_STYLES_FIX - - slider.setStyleSheet(MONTEREY_SLIDER_STYLES_FIX) - ``` diff --git a/src/superqt/sliders/__init__.py b/src/superqt/sliders/__init__.py index b0a47dc6..f05fc9f3 100644 --- a/src/superqt/sliders/__init__.py +++ b/src/superqt/sliders/__init__.py @@ -1,4 +1,7 @@ -from ._generic_slider import MONTEREY_SLIDER_STYLES_FIX +import warnings +from typing import Any + +from ._generic_slider import MONTEREY_SLIDER_STYLES_FIX as _MONTEREY_STYLES from ._labeled import ( QLabeledDoubleRangeSlider, QLabeledDoubleSlider, @@ -8,7 +11,6 @@ from ._sliders import QDoubleRangeSlider, QDoubleSlider, QRangeSlider __all__ = [ - "MONTEREY_SLIDER_STYLES_FIX", "QDoubleRangeSlider", "QDoubleSlider", "QLabeledDoubleRangeSlider", @@ -17,3 +19,16 @@ "QLabeledSlider", "QRangeSlider", ] + + +def __getattr__(name: str) -> Any: + if name == "MONTEREY_SLIDER_STYLES_FIX": + warnings.warn( + "MONTEREY_SLIDER_STYLES_FIX is deprecated and will be removed in a " + "future version. Call `applyMacStylePatch()` on the slider instead, " + "or set the `USE_MAC_SLIDER_PATCH=1` environment variable.", + DeprecationWarning, + stacklevel=2, + ) + return _MONTEREY_STYLES + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/tests/zz_test_sliders/test_generic_slider.py b/tests/zz_test_sliders/test_generic_slider.py index aae7ecc3..42f9cd7d 100644 --- a/tests/zz_test_sliders/test_generic_slider.py +++ b/tests/zz_test_sliders/test_generic_slider.py @@ -5,6 +5,7 @@ from qtpy.QtCore import QEvent, QPoint, QPointF, Qt from qtpy.QtWidgets import QStyle, QStyleOptionSlider +from superqt import sliders from superqt.sliders._generic_slider import _GenericSlider, _sliderValueFromPosition from ._testutil import _hover_event, _mouse_event, _wheel_event, skip_on_linux_qt6 @@ -185,3 +186,9 @@ def test_steps(gslider: _GenericSlider, qtbot): ) def test_slider_value_from_position(args, result): assert math.isclose(_sliderValueFromPosition(*args), result) + + +def test_monterey_styles_fix_deprecated(): + with pytest.warns(DeprecationWarning, match="applyMacStylePatch"): + style = sliders.MONTEREY_SLIDER_STYLES_FIX + assert "MONTEREY_SLIDER_STYLES_FIX" in style