Skip to content

Instantly share code, notes, and snippets.

@rfletchr
Last active June 12, 2024 22:51
Show Gist options
  • Save rfletchr/649eac7a61525d03474220c6cb709f9e to your computer and use it in GitHub Desktop.
Save rfletchr/649eac7a61525d03474220c6cb709f9e to your computer and use it in GitHub Desktop.
A PySide slider for floating point values.
from PySide6 import QtWidgets
"""
This is a simple "trick" that uses "scaled integer arithmatic" to internally represent floating point values as integers.
Using this coversion it makes it extremely simple to use the standard interger slider to work on floating point numbers.
given a spinner with 2 decimal places.
rounded = round(1.1111, 2)
>> 1.11
scaled = rounded * pow(10, 2)
>> 111.0
value = int(scaled)
111
coversion back to float is simply
value / pow(10, 2)
1.11
essentially all this is doing is shifting the decimal point around.
"""
class DoubleSlider(QtWidgets.QSlider):
def __init__(self, parent=None, decimals=2):
super().__init__(parent)
self._decimals = decimals
def setRange(self, minimum: float, maximum: float):
super().setRange(self._to_integer(minimum), self._to_integer(maximum))
def setMinimum(self, minimum: float):
super().setMinimum(self._to_integer(minimum))
def setMaximum(self, maximum: float):
super().setMaximum(self._to_integer(maximum))
def minimum(self) -> float:
return self._to_float(super().minimum())
def maximum(self) -> float:
return self._to_float(super().maximum())
def setValue(self, value: float):
super().setValue(self._to_integer(value))
def value(self) -> float:
return self._to_float(super().value())
def _to_integer(self, value: float) -> int:
return int(round(value, self._decimals) * pow(10, self._decimals))
def _to_float(self, value: int) -> float:
return float(value) / pow(10, self._decimals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment