"""Native number inputs and scrollbars with usable click targets.""" from PySide6 import QtCore as C, QtGui as G, QtWidgets as W import time class FocusWheelMixin: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # StrongFocus permits click/keyboard focus, but never wheel focus. self.setFocusPolicy(C.Qt.FocusPolicy.StrongFocus) def wheelEvent(self, event): if not self.hasFocus(): event.ignore() return super().wheelEvent(event) class SpinBox(FocusWheelMixin, W.QSpinBox): pass class DoubleSpinBox(FocusWheelMixin, W.QDoubleSpinBox): pass class ComboBox(W.QComboBox): """Size popups for their text, independently of narrow table columns.""" def __init__(self, parent=None): self._text_width = None self._text_alignment = None super().__init__(parent) self.setSizeAdjustPolicy(W.QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon) self.setMinimumContentsLength(6) self.setMaxVisibleItems(12) view = W.QListView(self) view.setTextElideMode(C.Qt.TextElideMode.ElideNone) view.setHorizontalScrollBarPolicy(C.Qt.ScrollBarPolicy.ScrollBarAsNeeded) view.setHorizontalScrollMode(W.QAbstractItemView.ScrollMode.ScrollPerPixel) self.setView(view) for signal in (self.model().dataChanged, self.model().rowsInserted, self.model().rowsRemoved, self.model().modelReset): signal.connect(self.invalidate_width) def invalidate_width(self, *args): self._text_width = None self.updateGeometry() def text_width(self): if self._text_width is None: self._text_width = max((self.fontMetrics().horizontalAdvance(self.itemText(i)) for i in range(self.count())), default=0) return self._text_width def sizeHint(self): hint = super().sizeHint() hint.setWidth(max(120, hint.width(), min(360, self.text_width() + 48))) return hint def minimumSizeHint(self): hint = super().minimumSizeHint() hint.setWidth(max(120, hint.width(), min(260, self.text_width() + 48))) return hint def changeEvent(self, event): if event.type() in (C.QEvent.Type.FontChange, C.QEvent.Type.StyleChange): self.invalidate_width() super().changeEvent(event) def showPopup(self): view = self.view() screen = self.screen().availableGeometry() scrollbar = view.verticalScrollBar().sizeHint().width() content = max(self.text_width() + 16, view.sizeHintForColumn(0)) width = min(screen.width(), max(self.width(), content + scrollbar + 2 * view.frameWidth() + 8)) popup = view.window() frame = popup.frameWidth() if isinstance(popup, W.QFrame) else 0 view.setMinimumWidth(max(0, width - 2 * frame)) super().showPopup() # QComboBox resets this policy while opening its popup. view.setHorizontalScrollBarPolicy(C.Qt.ScrollBarPolicy.ScrollBarAsNeeded) popup.resize(width, popup.height()) view.doItemsLayout() if view.horizontalScrollBar().maximum() > 0: popup.resize(width, min(screen.height(), popup.height() + view.horizontalScrollBar().sizeHint().height())) popup.move(min(max(popup.x(), screen.left()), screen.right() - popup.width() + 1), min(max(popup.y(), screen.top()), screen.bottom() - popup.height() + 1)) def event(self, event): if event.type() == C.QEvent.Type.ToolTip and self.currentText(): text = self.currentText() if self.toolTip() and self.toolTip() != text: text += "\n" + self.toolTip() W.QToolTip.showText(event.globalPos(), text, self) return True return super().event(event) def setTextAlignment(self, alignment): self._text_alignment = alignment self.update() def paintEvent(self, event): if self._text_alignment is None: return super().paintEvent(event) painter = W.QStylePainter(self) option = W.QStyleOptionComboBox() self.initStyleOption(option) option.textAlignment = self._text_alignment painter.drawComplexControl(W.QStyle.ComplexControl.CC_ComboBox, option) painter.drawControl(W.QStyle.ControlElement.CE_ComboBoxLabel, option) class RowBatch(C.QObject): """Create Qt rows in short event-loop slices, keeping input responsive.""" def __init__(self, parent): super().__init__(parent) self.timer = C.QTimer(self) self.timer.setInterval(1) self.timer.timeout.connect(self.tick) self.running = False def start(self, rows, apply, finished): self.stop() self.rows, self.apply, self.finished = iter(rows), apply, finished self.running = True self.tick() if self.running: self.timer.start() def stop(self): self.timer.stop() self.running = False @C.Slot() def tick(self): until = time.perf_counter() + .008 count = 0 while self.running and count < 24 and time.perf_counter() < until: try: row = next(self.rows) except StopIteration: self.stop() self.finished() return self.apply(row) count += 1 class IntegerInput(W.QLineEdit): valueChanged = C.Signal(int) def __init__(self): super().__init__() self._value, self._minimum, self._maximum = 0, 0, 2147483647 self._wheel_delta = 0 self.setFocusPolicy(C.Qt.FocusPolicy.StrongFocus) self.setValidator(G.QIntValidator(self._minimum, self._maximum, self)) self.setText("0") self.setMinimumWidth(76) self.textChanged.connect(self.accept_number) self.editingFinished.connect(self.finish_number) def value(self): return self._value def setValue(self, value): value = min(self._maximum, max(self._minimum, int(value))) changed = value != self._value # Signal blockers must not prevent updates to the stored numeric value. self._value = value self.setText(str(value)) if changed: self.valueChanged.emit(value) def setRange(self, minimum, maximum): self._minimum, self._maximum = int(minimum), int(maximum) self.validator().setRange(self._minimum, self._maximum) self.setValue(self._value) def setMinimum(self, minimum): self.setRange(minimum, self._maximum) def accept_number(self, text): if self.hasAcceptableInput(): value = int(text) if value != self._value: self._value = value self.valueChanged.emit(value) def finish_number(self): self.setValue(self._value) def wheelEvent(self, event): if not self.hasFocus() or not event.angleDelta().y(): event.ignore() return self._wheel_delta += event.angleDelta().y() steps = int(self._wheel_delta / 120) self._wheel_delta -= steps * 120 if steps: if event.modifiers() & C.Qt.KeyboardModifier.ControlModifier: steps *= 10 self.setValue(self.value() + steps) event.accept() def focusOutEvent(self, event): self._wheel_delta = 0 super().focusOutEvent(event) class NativeScrollStyle(W.QProxyStyle): def pixelMetric(self, metric, option=None, widget=None): value = super().pixelMetric(metric, option, widget) if metric == W.QStyle.PixelMetric.PM_ScrollBarExtent: return max(22, value) if metric == W.QStyle.PixelMetric.PM_ScrollBarSliderMin: return max(30, value) return value def styleHint(self, hint, option=None, widget=None, returnData=None): if hint == W.QStyle.StyleHint.SH_ScrollBar_Transient: return 0 return super().styleHint(hint, option, widget, returnData) class ScrollbarStyler(C.QObject): def __init__(self, app): super().__init__(app) self.scroll_style = NativeScrollStyle(W.QStyleFactory.create("Fusion")) self.scroll_style.setParent(self) def eventFilter(self, widget, event): if event.type() == C.QEvent.Type.Polish and isinstance(widget, W.QScrollBar) and not getattr(widget, "_ranch_scrollbar", False): widget._ranch_scrollbar = True widget.setStyle(self.scroll_style) if widget.orientation() == C.Qt.Orientation.Horizontal: widget.setFixedHeight(22) else: widget.setFixedWidth(22) return False def use_native_scrollbars(): app = W.QApplication.instance() if app is None or getattr(app, "_ranch_scrollbar_styler", None) is not None: return styler = ScrollbarStyler(app) app._ranch_scrollbar_styler = styler app.installEventFilter(styler)