From f815e21aa83c4fc68519bfd35219dffe743c190d Mon Sep 17 00:00:00 2001 From: EKNr1 Date: Sat, 25 Jan 2025 12:58:09 +0100 Subject: [PATCH] Improved calculation of slider value when the slider gets clicked and added comments. --- wobuzz/ui/track_progress_slider.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/wobuzz/ui/track_progress_slider.py b/wobuzz/ui/track_progress_slider.py index 5ee04d9..e687ff8 100644 --- a/wobuzz/ui/track_progress_slider.py +++ b/wobuzz/ui/track_progress_slider.py @@ -2,7 +2,7 @@ from PyQt6.QtCore import Qt from PyQt6.QtGui import QMouseEvent -from PyQt6.QtWidgets import QSlider +from PyQt6.QtWidgets import QSlider, QStyle, QStyleOptionSlider class TrackProgressSlider(QSlider): @@ -11,16 +11,29 @@ class TrackProgressSlider(QSlider): self.dragged = False + option = QStyleOptionSlider() + style = self.style() + + self.handle_width = style.pixelMetric(QStyle.PixelMetric.PM_SliderThickness, option, self) + self.sliderPressed.connect(self.on_press) self.sliderReleased.connect(self.on_release) def mousePressEvent(self, event: QMouseEvent): + # we need a custom press event bc. PyQt doesn't set the slider position when clicked if event.button() == Qt.MouseButton.LeftButton: event.accept() x = event.pos().x() - value = self.maximum() * x // self.width() + # old value calculation: + # value = self.maximum() * x // self.width() + # but we need that calculation because the handle width is limiting the range, and we need to set + # the slider handle's center to the click position, not the start of the handle + # (self.width() - self.handle_width) calculates the usable width and + # (x - self.handle_width // 2) offsets the position by minus half of the handle width + value = self.maximum() * (x - self.handle_width // 2) // (self.width() - self.handle_width) + self.setValue(value) return super().mousePressEvent(event)