mirror of
https://github.com/bec-project/bec_widgets.git
synced 2026-11-20 00:04:16 +01:00
refactor(hover_widget): replace WidgetTooltip with the shared hover card
This commit is contained in:
1 parent
ad99f801ee
commit
d918df79d9
13 files changed
+537
-490
No files matched your search
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
A frameless card window that opens next to a widget, with any content widget, and the controller
|
||||
that opens it on hover. Used by the status bar pills, the client info in the status bar and as a
|
||||
rich tooltip.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from enum import StrEnum
|
||||
from typing import Callable
|
||||
|
||||
import shiboken6
|
||||
from qtpy.QtCore import QEvent, QObject, QPoint, QRect, Qt, QTimer
|
||||
from qtpy.QtGui import QColor, QCursor, QGuiApplication
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QFrame,
|
||||
QGraphicsDropShadowEffect,
|
||||
QLabel,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.theme_utils import css, theme_colors
|
||||
|
||||
# focus the user gave the anchor on purpose, as opposed to Qt focusing it on window activation
|
||||
KEYBOARD_FOCUS_REASONS = (Qt.FocusReason.TabFocusReason, Qt.FocusReason.BacktabFocusReason)
|
||||
|
||||
|
||||
class CardAlign(StrEnum):
|
||||
"""Where a hover card opens relative to its anchor."""
|
||||
|
||||
LEFT = "left" # left edges aligned
|
||||
CENTER = "center" # centred on the anchor, e.g. a wide label
|
||||
|
||||
|
||||
class HoverCard(QWidget):
|
||||
"""
|
||||
The frameless card that opens next to a widget, with any content widget. It never takes
|
||||
keyboard focus from the main window. A HoverCardController opens and closes it on hover; as a
|
||||
rich tooltip its owner shows it with show_near and hides it. A non-activating Tool window
|
||||
rather than a ToolTip one, so its buttons take clicks on every platform.
|
||||
|
||||
Args:
|
||||
owner(QWidget): The widget the card belongs to (its parent).
|
||||
content(QWidget | None): The widget shown in the card; can be set later with set_content.
|
||||
width(int | None): Fixed width of the card frame; None follows the content.
|
||||
object_name(str): Object name of the card frame, for its style sheet.
|
||||
hide_on_leave(bool): Hide the card when the cursor leaves it, like a tooltip.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
owner: QWidget,
|
||||
content: QWidget | None = None,
|
||||
width: int | None = None,
|
||||
object_name: str = "status_hover_card",
|
||||
hide_on_leave: bool = False,
|
||||
):
|
||||
super().__init__(
|
||||
owner,
|
||||
Qt.WindowType.Tool
|
||||
| Qt.WindowType.FramelessWindowHint
|
||||
| Qt.WindowType.WindowDoesNotAcceptFocus
|
||||
# the card draws its own rounded shadow; the native one (macOS) is computed for the
|
||||
# whole translucent window and shows as a square-cornered band around the card
|
||||
| Qt.WindowType.NoDropShadowWindowHint,
|
||||
)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
|
||||
outer = self.outer_layout = QVBoxLayout(self)
|
||||
outer.setContentsMargins(12, 12, 12, 12) # room for the shadow
|
||||
self.card = QFrame(self)
|
||||
self.card.setObjectName(object_name)
|
||||
if width is not None:
|
||||
self.card.setFixedWidth(width)
|
||||
shadow = QGraphicsDropShadowEffect(self.card)
|
||||
shadow.setBlurRadius(24)
|
||||
shadow.setOffset(0, 4)
|
||||
shadow.setColor(QColor(0, 0, 0, 70))
|
||||
self.card.setGraphicsEffect(shadow)
|
||||
self.inner_layout = QVBoxLayout(self.card)
|
||||
self.inner_layout.setContentsMargins(14, 14, 14, 14)
|
||||
outer.addWidget(self.card)
|
||||
self.content: QWidget | None = None
|
||||
self.hint: QLabel | None = None
|
||||
self.hide_on_leave = hide_on_leave
|
||||
if content is not None:
|
||||
self.set_content(content)
|
||||
self.refresh_style()
|
||||
|
||||
def set_content(self, content: QWidget) -> None:
|
||||
"""Show a widget in the card, in place of the previous content."""
|
||||
if self.content is not None:
|
||||
self.inner_layout.removeWidget(self.content)
|
||||
self.content = content
|
||||
content.setParent(self.card)
|
||||
self.inner_layout.insertWidget(0, content)
|
||||
|
||||
def add_hint(self, text: str) -> QLabel:
|
||||
"""Add a small muted line below the content, e.g. how to dock the widget."""
|
||||
if self.hint is None:
|
||||
self.hint = QLabel(self.card)
|
||||
self.hint.setObjectName("status_card_hint")
|
||||
self.inner_layout.addWidget(self.hint)
|
||||
self.refresh_style()
|
||||
self.hint.setText(text)
|
||||
return self.hint
|
||||
|
||||
def show_near(self, global_pos: QPoint, offset: QPoint | None = None) -> None:
|
||||
"""
|
||||
Show the card next to a global position, below and to the right of it by default. It
|
||||
flips to the other side of the position where it would leave the screen, and stays on
|
||||
the screen.
|
||||
|
||||
Args:
|
||||
global_pos(QPoint): The position, e.g. the cursor or the centre of a button.
|
||||
offset(QPoint, optional): Distance of the card frame from the position. Defaults to
|
||||
QPoint(12, 16).
|
||||
"""
|
||||
self.refresh_style()
|
||||
self.adjustSize()
|
||||
offset = offset or QPoint(12, 16)
|
||||
screen = QGuiApplication.screenAt(global_pos) or QGuiApplication.primaryScreen()
|
||||
area = screen.availableGeometry()
|
||||
# the frame sits inside the window's shadow margins
|
||||
margins = self.outer_layout.contentsMargins()
|
||||
width, height = self.width(), self.height()
|
||||
x = global_pos.x() + offset.x() - margins.left()
|
||||
y = global_pos.y() + offset.y() - margins.top()
|
||||
if x + width > area.right():
|
||||
x = global_pos.x() - abs(offset.x()) - width + margins.right()
|
||||
if y + height > area.bottom():
|
||||
y = global_pos.y() - abs(offset.y()) - height + margins.bottom()
|
||||
x = max(area.left(), min(x, area.right() - width + 1))
|
||||
y = max(area.top(), min(y, area.bottom() - height + 1))
|
||||
self.move(x, y)
|
||||
self.show()
|
||||
self.raise_()
|
||||
|
||||
def leaveEvent(self, event): # pylint: disable=invalid-name
|
||||
super().leaveEvent(event)
|
||||
if self.hide_on_leave:
|
||||
self.hide()
|
||||
|
||||
def refresh_style(self) -> None:
|
||||
"""Re-read the theme colours."""
|
||||
colors = theme_colors()
|
||||
self.card.setStyleSheet(
|
||||
f"#{self.card.objectName()} {{ background: {css(colors['card'])};"
|
||||
f" border: 1px solid {css(colors['border'])}; border-radius: 8px; }}"
|
||||
f"#status_card_hint {{ color: {css(colors['muted'])}; font-size: 11px; }}"
|
||||
)
|
||||
|
||||
|
||||
class HoverCardController(QObject):
|
||||
"""
|
||||
Opens a HoverCard above an anchor widget on hover and keeps it open while the cursor is over
|
||||
the anchor, the card, the gap between them or one of the extra widgets, while the anchor has
|
||||
keyboard focus, or while a popup or dialog of the card is open. The card closes GRACE_MS after
|
||||
the cursor has left, on Esc, and when the application is deactivated. It is kept on the
|
||||
screen of the anchor and follows it when either moves or changes size.
|
||||
|
||||
Only a cursor poll decides inside or outside: Enter and Leave events are not reliable while
|
||||
the card window is shown (e.g. on macOS).
|
||||
|
||||
Args:
|
||||
anchor(QWidget): The widget the card opens above; its Enter opens the card.
|
||||
card(HoverCard): The card window.
|
||||
keep_open(Callable[[], bool] | None): Asked on each poll; True keeps the card open.
|
||||
can_open(Callable[[], bool] | None): Asked before opening; False keeps the card closed.
|
||||
on_close(Callable[[], None] | None): Called when the card closes.
|
||||
align(CardAlign): LEFT aligns the card to the anchor's left edge, CENTER centres it on
|
||||
the anchor (for a wide anchor such as the client info label).
|
||||
"""
|
||||
|
||||
GRACE_MS = 250 # how long the cursor may be outside before the card closes
|
||||
POLL_MS = 90 # cursor check while hovered or open
|
||||
HOVER_TOLERANCE = 4 # px around anchor, extras and card that still count as inside
|
||||
GAP = 8 # px between the anchor and the card
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
anchor: QWidget,
|
||||
card: HoverCard,
|
||||
keep_open: Callable[[], bool] | None = None,
|
||||
can_open: Callable[[], bool] | None = None,
|
||||
on_close: Callable[[], None] | None = None,
|
||||
align: CardAlign | str = CardAlign.LEFT,
|
||||
):
|
||||
super().__init__(anchor)
|
||||
self.anchor = anchor
|
||||
self.card = card
|
||||
self.align = CardAlign(align)
|
||||
self._keep_open = keep_open
|
||||
self._can_open = can_open
|
||||
self._on_close = on_close
|
||||
self._extras: list[QWidget] = []
|
||||
self._outside_since: float | None = None
|
||||
self.poll = QTimer(self)
|
||||
self.poll.setInterval(self.POLL_MS)
|
||||
self.poll.timeout.connect(self.check_cursor)
|
||||
for widget in (anchor, card):
|
||||
widget.installEventFilter(self)
|
||||
app = QGuiApplication.instance()
|
||||
self._app_connected = app is not None
|
||||
if app is not None:
|
||||
app.applicationStateChanged.connect(self._on_application_state)
|
||||
|
||||
@property
|
||||
def outside_since(self) -> float | None:
|
||||
"""time.monotonic() when the cursor left, or None while it is inside."""
|
||||
return self._outside_since
|
||||
|
||||
def add_extra(self, widget: QWidget) -> None:
|
||||
"""Count a widget next to the anchor as inside, e.g. a Stop button; it does not open it."""
|
||||
self._extras.append(widget)
|
||||
widget.installEventFilter(self)
|
||||
|
||||
def start_watching(self) -> None:
|
||||
"""Start the cursor poll; repeated (sometimes synthetic) Enter events do not restart it."""
|
||||
if not self.poll.isActive():
|
||||
self._outside_since = None
|
||||
self.poll.start()
|
||||
|
||||
def open(self) -> None:
|
||||
"""Show the card above the anchor."""
|
||||
if self._can_open is not None and not self._can_open():
|
||||
return
|
||||
self.start_watching()
|
||||
if self.card.isVisible():
|
||||
return
|
||||
self.card.refresh_style() # the theme may have changed while it was closed
|
||||
self.card.adjustSize()
|
||||
self.place()
|
||||
self.card.show()
|
||||
|
||||
def close(self) -> None:
|
||||
"""Hide the card and stop watching the cursor."""
|
||||
if self._on_close is not None:
|
||||
self._on_close()
|
||||
self.leave()
|
||||
|
||||
def leave(self) -> None:
|
||||
"""Hide the card without the on_close hook (the cursor left)."""
|
||||
self.poll.stop()
|
||||
self._outside_since = None
|
||||
self.card.hide()
|
||||
set_hovered = getattr(self.anchor, "set_hovered", None)
|
||||
if callable(set_hovered):
|
||||
set_hovered(False)
|
||||
|
||||
def place(self) -> None:
|
||||
"""
|
||||
Put the card above the anchor, left-aligned to it (or centred), with its bottom at the
|
||||
anchor, and keep it inside the available geometry of the anchor's screen.
|
||||
"""
|
||||
margin = self.card.outer_layout.contentsMargins()
|
||||
top_left = self.anchor.mapToGlobal(QPoint(0, 0))
|
||||
if self.align == CardAlign.CENTER:
|
||||
x = top_left.x() + (self.anchor.width() - self.card.width()) // 2
|
||||
else:
|
||||
x = top_left.x() - margin.left()
|
||||
y = top_left.y() - self.card.height() + margin.bottom() - self.GAP
|
||||
screen = self.anchor.screen() or QGuiApplication.primaryScreen()
|
||||
if screen is not None:
|
||||
area = screen.availableGeometry()
|
||||
x = max(area.left(), min(x, area.right() - self.card.width() + 1))
|
||||
y = max(area.top(), min(y, area.bottom() - self.card.height() + 1))
|
||||
self.card.move(x, y)
|
||||
|
||||
def _global_rect(self, widget: QWidget) -> QRect:
|
||||
rect = QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size())
|
||||
tol = self.HOVER_TOLERANCE
|
||||
return rect.adjusted(-tol, -tol, tol, tol)
|
||||
|
||||
def hovered(self) -> bool:
|
||||
"""Whether the cursor is over the anchor, an extra, the card, or the gap to the card."""
|
||||
pos = QCursor.pos()
|
||||
widgets = [self.anchor, *self._extras]
|
||||
rects = [self._global_rect(w) for w in widgets if w.isVisible()]
|
||||
if self.card.isVisible():
|
||||
card = self._global_rect(self.card.card)
|
||||
anchor = self._global_rect(self.anchor)
|
||||
rects.append(card)
|
||||
rects.append(
|
||||
QRect(anchor.left(), card.bottom(), anchor.width(), anchor.top() - card.bottom())
|
||||
)
|
||||
return any(rect.contains(pos) for rect in rects)
|
||||
|
||||
def _owns(self, widget: QWidget | None) -> bool:
|
||||
owner = widget.parentWidget() if widget is not None else None
|
||||
if owner is None:
|
||||
return False
|
||||
roots = [self.card, self.anchor, *self._extras]
|
||||
host = self.anchor.parentWidget()
|
||||
if host is not None:
|
||||
roots.append(host)
|
||||
return any(owner is root or root.isAncestorOf(owner) for root in roots)
|
||||
|
||||
def own_window_open(self) -> bool:
|
||||
"""
|
||||
Whether a popup or a modal dialog of the card or the anchor is open, e.g. the arrow menu
|
||||
of a Stop in the card or a confirmation dialog of its content.
|
||||
"""
|
||||
return self._owns(QApplication.activePopupWidget()) or self._owns(
|
||||
QApplication.activeModalWidget()
|
||||
)
|
||||
|
||||
def _anchor_has_keyboard_focus(self) -> bool:
|
||||
return bool(getattr(self.anchor, "keyboard_focus", False))
|
||||
|
||||
@SafeSlot()
|
||||
def check_cursor(self) -> None:
|
||||
"""The poll: close the card GRACE_MS after the cursor has left."""
|
||||
if self.hovered() or self._anchor_has_keyboard_focus() or self.own_window_open():
|
||||
self._outside_since = None
|
||||
return
|
||||
if self._keep_open is not None and self._keep_open():
|
||||
return
|
||||
now = time.monotonic()
|
||||
if self._outside_since is None:
|
||||
self._outside_since = now
|
||||
elif now - self._outside_since >= self.GRACE_MS / 1000:
|
||||
self.leave()
|
||||
|
||||
@SafeSlot(object)
|
||||
def _on_application_state(self, state) -> None:
|
||||
if state != Qt.ApplicationState.ApplicationActive:
|
||||
self.close()
|
||||
|
||||
def eventFilter(self, obj, event): # pylint: disable=invalid-name
|
||||
kind = event.type()
|
||||
# Qt can deliver a late Enter to a widget that was hidden or closed in the meantime
|
||||
if kind == QEvent.Type.Enter and obj is self.anchor and self.anchor.isVisible():
|
||||
set_hovered = getattr(self.anchor, "set_hovered", None)
|
||||
if callable(set_hovered):
|
||||
set_hovered(True)
|
||||
self.open()
|
||||
elif kind == QEvent.Type.Enter and obj is self.card:
|
||||
self.open()
|
||||
elif kind == QEvent.Type.Enter and obj in self._extras:
|
||||
self.start_watching()
|
||||
elif kind == QEvent.Type.Leave and obj is self.anchor and not self.card.isVisible():
|
||||
set_hovered = getattr(self.anchor, "set_hovered", None)
|
||||
if callable(set_hovered):
|
||||
set_hovered(False)
|
||||
elif (
|
||||
kind == QEvent.Type.FocusIn
|
||||
and obj is self.anchor
|
||||
and event.reason() in KEYBOARD_FOCUS_REASONS
|
||||
):
|
||||
self.open()
|
||||
elif kind == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Escape:
|
||||
self.close()
|
||||
return True
|
||||
elif kind in (QEvent.Type.Move, QEvent.Type.Resize) and self.card.isVisible():
|
||||
# the card grows with its content, and the anchor moves when a widget next to it
|
||||
# slides in: keep the card bottom-anchored above the anchor
|
||||
if obj is self.anchor or obj is self.card:
|
||||
self.place()
|
||||
return super().eventFilter(obj, event)
|
||||
|
||||
def anchor_window_deactivated(self) -> None:
|
||||
"""Close unless the card itself or one of its popups or dialogs took the activation."""
|
||||
if not self.card.isActiveWindow() and not self.own_window_open():
|
||||
self.close()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""Stop the poll, close the card and stop listening to the anchor, card and extras."""
|
||||
self.poll.stop()
|
||||
for widget in (self.anchor, self.card, *self._extras):
|
||||
if shiboken6.isValid(widget):
|
||||
widget.removeEventFilter(self)
|
||||
app = QGuiApplication.instance()
|
||||
if app is not None and self._app_connected:
|
||||
self._app_connected = False
|
||||
try:
|
||||
app.applicationStateChanged.disconnect(self._on_application_state)
|
||||
except (TypeError, RuntimeError):
|
||||
pass
|
||||
self.card.hide()
|
||||
@@ -14,7 +14,7 @@ from qtpy.QtWidgets import (
|
||||
)
|
||||
|
||||
from bec_widgets.utils.error_popups import SafeProperty
|
||||
from bec_widgets.widgets.containers.main_window.addons.hover_widget import WidgetTooltip
|
||||
from bec_widgets.utils.hover_card import HoverCard
|
||||
|
||||
|
||||
class CollapsibleSection(QWidget):
|
||||
@@ -44,7 +44,7 @@ class CollapsibleSection(QWidget):
|
||||
self.title = title
|
||||
self.content_widget = None
|
||||
self._help_text = tooltip
|
||||
self._help_tooltip: WidgetTooltip | None = None
|
||||
self._help_tooltip: HoverCard | None = None
|
||||
self.destroyed.connect(self._cleanup_help_tooltip)
|
||||
self.setAcceptDrops(True)
|
||||
self._expanded = True
|
||||
@@ -187,7 +187,9 @@ class CollapsibleSection(QWidget):
|
||||
help_label.setWordWrap(True)
|
||||
help_label.setMinimumWidth(220)
|
||||
help_label.setMaximumWidth(320)
|
||||
self._help_tooltip = WidgetTooltip(help_label)
|
||||
self._help_tooltip = HoverCard(
|
||||
self, help_label, object_name="section_help_card", hide_on_leave=True
|
||||
)
|
||||
|
||||
anchor = self.header_info_button.mapToGlobal(self.header_info_button.rect().center())
|
||||
self._help_tooltip.show_near(anchor)
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
"""A frameless window that behaves like a tooltip, with any content widget."""
|
||||
|
||||
from qtpy import QtGui, QtWidgets
|
||||
from qtpy.QtCore import QPoint, Qt
|
||||
from qtpy.QtWidgets import QApplication, QFrame, QVBoxLayout, QWidget
|
||||
|
||||
|
||||
class WidgetTooltip(QWidget):
|
||||
"""Frameless, always-on-top window that behaves like a tooltip."""
|
||||
|
||||
def __init__(self, content: QWidget) -> None:
|
||||
super().__init__(
|
||||
None,
|
||||
Qt.WindowType.ToolTip
|
||||
| Qt.WindowType.FramelessWindowHint
|
||||
| Qt.WindowType.WindowStaysOnTopHint,
|
||||
)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
self.setMouseTracking(True)
|
||||
self.content = content
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(14, 14, 14, 14)
|
||||
|
||||
self._card = QFrame(self)
|
||||
self._card.setObjectName("WidgetTooltipCard")
|
||||
card_layout = QVBoxLayout(self._card)
|
||||
card_layout.setContentsMargins(12, 10, 12, 10)
|
||||
card_layout.addWidget(self.content)
|
||||
|
||||
shadow = QtWidgets.QGraphicsDropShadowEffect(self._card)
|
||||
shadow.setBlurRadius(18)
|
||||
shadow.setOffset(0, 2)
|
||||
shadow.setColor(QtGui.QColor(0, 0, 0, 140))
|
||||
self._card.setGraphicsEffect(shadow)
|
||||
|
||||
layout.addWidget(self._card)
|
||||
self.apply_theme()
|
||||
self.adjustSize()
|
||||
|
||||
def leaveEvent(self, _event) -> None:
|
||||
self.hide()
|
||||
|
||||
def apply_theme(self) -> None:
|
||||
palette = QApplication.palette()
|
||||
base = palette.color(QtGui.QPalette.ColorRole.Base)
|
||||
text = palette.color(QtGui.QPalette.ColorRole.Text)
|
||||
border = palette.color(QtGui.QPalette.ColorRole.Mid)
|
||||
background = QtGui.QColor(base)
|
||||
background.setAlpha(242)
|
||||
self._card.setStyleSheet(f"""
|
||||
QFrame#WidgetTooltipCard {{
|
||||
background: {background.name(QtGui.QColor.NameFormat.HexArgb)};
|
||||
border: 1px solid {border.name()};
|
||||
border-radius: 12px;
|
||||
}}
|
||||
QFrame#WidgetTooltipCard QLabel {{
|
||||
color: {text.name()};
|
||||
background: transparent;
|
||||
}}
|
||||
""")
|
||||
|
||||
def show_above(self, global_pos: QPoint, offset: int = 8) -> None:
|
||||
"""
|
||||
Show the tooltip above a global position, adjusting to stay within screen bounds.
|
||||
|
||||
Args:
|
||||
global_pos(QPoint): The global position to show above.
|
||||
offset(int, optional): The vertical offset from the global position. Defaults to 8 pixels.
|
||||
"""
|
||||
self.apply_theme()
|
||||
self.adjustSize()
|
||||
screen = QApplication.screenAt(global_pos) or QApplication.primaryScreen()
|
||||
screen_geo = screen.availableGeometry()
|
||||
geom = self.geometry()
|
||||
|
||||
x = global_pos.x() - geom.width() // 2
|
||||
y = global_pos.y() - geom.height() - offset
|
||||
|
||||
self._navigate_screen_coordinates(screen_geo, geom, x, y)
|
||||
|
||||
def show_near(self, global_pos: QPoint, offset: QPoint | None = None) -> None:
|
||||
"""
|
||||
Show the tooltip near a global position, adjusting to stay within screen bounds.
|
||||
By default, it will try to show below and to the right of the position,
|
||||
but if that would cause it to go off-screen, it will flip to the other side.
|
||||
|
||||
Args:
|
||||
global_pos(QPoint): The global position to show near.
|
||||
offset(QPoint, optional): The offset from the global position. Defaults to QPoint(12, 16).
|
||||
"""
|
||||
|
||||
self.apply_theme()
|
||||
self.adjustSize()
|
||||
offset = offset or QPoint(12, 16)
|
||||
screen = QApplication.screenAt(global_pos) or QApplication.primaryScreen()
|
||||
screen_geo = screen.availableGeometry()
|
||||
geom = self.geometry()
|
||||
|
||||
x = global_pos.x() + offset.x()
|
||||
y = global_pos.y() + offset.y()
|
||||
|
||||
if x + geom.width() > screen_geo.right():
|
||||
x = global_pos.x() - geom.width() - abs(offset.x())
|
||||
if y + geom.height() > screen_geo.bottom():
|
||||
y = global_pos.y() - geom.height() - abs(offset.y())
|
||||
|
||||
self._navigate_screen_coordinates(screen_geo, geom, x, y)
|
||||
|
||||
def _navigate_screen_coordinates(self, screen_geo, geom, x, y):
|
||||
x = max(screen_geo.left(), min(x, screen_geo.right() - geom.width()))
|
||||
y = max(screen_geo.top(), min(y, screen_geo.bottom() - geom.height()))
|
||||
|
||||
self.move(x, y)
|
||||
self.show()
|
||||
self.raise_()
|
||||
@@ -14,12 +14,11 @@ from qtpy.QtWidgets import QWidget
|
||||
|
||||
from bec_widgets.utils.bec_connector import Worker
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.hover_card import HoverCard
|
||||
from bec_widgets.widgets.containers.main_window.addons.status_pill import ( # noqa: F401
|
||||
KEYBOARD_FOCUS_REASONS,
|
||||
PILL_FILL_MIN,
|
||||
PILL_MODES,
|
||||
PILL_WIDTHS,
|
||||
HoverCard,
|
||||
Reveal,
|
||||
StatusPillItem,
|
||||
ToolIndicator,
|
||||
|
||||
@@ -3,13 +3,11 @@ Status-bar pills for the main window: a small state bar that opens a card with i
|
||||
hover. A pill item shows a ToolIndicator (severity, summary, badge, progress); subclasses feed the
|
||||
indicator and give the card its content, e.g. the scan pill with the full ScanProgressBar.
|
||||
|
||||
The hover handling lives in HoverCardController, which works for any trigger widget, also a plain
|
||||
label (the client info in the status bar).
|
||||
The card and its hover handling live in bec_widgets.utils.hover_card.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import Callable
|
||||
@@ -22,30 +20,19 @@ from qtpy.QtCore import (
|
||||
QParallelAnimationGroup,
|
||||
QPoint,
|
||||
QPropertyAnimation,
|
||||
QRect,
|
||||
QRectF,
|
||||
QSettings,
|
||||
Qt,
|
||||
QTimer,
|
||||
Signal,
|
||||
)
|
||||
from qtpy.QtGui import QAction, QActionGroup, QColor, QCursor, QGuiApplication, QPainter, QPen
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QFrame,
|
||||
QGraphicsDropShadowEffect,
|
||||
QGraphicsOpacityEffect,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QMenu,
|
||||
QSizePolicy,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
from qtpy.QtGui import QAction, QActionGroup, QPainter, QPen
|
||||
from qtpy.QtWidgets import QGraphicsOpacityEffect, QHBoxLayout, QMenu, QSizePolicy, QWidget
|
||||
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.theme_utils import css, theme_colors
|
||||
from bec_widgets.utils.hover_card import KEYBOARD_FOCUS_REASONS, HoverCard, HoverCardController
|
||||
from bec_widgets.utils.theme_utils import theme_colors
|
||||
from bec_widgets.widgets.progress.stage_bar import BarMode, Chip, StageBar, Tone
|
||||
|
||||
logger = bec_logger.logger
|
||||
@@ -55,16 +42,6 @@ PILL_WIDTHS = {"compact": (150, 200), "normal": (280, 380), "wide": (480, 620)}
|
||||
PILL_FILL_MIN = 220
|
||||
PILL_MODES = ("compact", "normal", "wide", "fill")
|
||||
|
||||
# focus the user gave the pill on purpose, as opposed to Qt focusing it on window activation
|
||||
KEYBOARD_FOCUS_REASONS = (Qt.FocusReason.TabFocusReason, Qt.FocusReason.BacktabFocusReason)
|
||||
|
||||
|
||||
class CardAlign(StrEnum):
|
||||
"""Where a hover card opens relative to its anchor."""
|
||||
|
||||
LEFT = "left" # left edges aligned
|
||||
CENTER = "center" # centred on the anchor, e.g. a wide label
|
||||
|
||||
|
||||
class ToolSeverity(StrEnum):
|
||||
"""How a status-bar pill rates what it reports."""
|
||||
@@ -289,311 +266,6 @@ class StatusBarPill(StageBar):
|
||||
painter.end()
|
||||
|
||||
|
||||
class HoverCard(QWidget):
|
||||
"""
|
||||
The frameless card that opens above a status-bar widget, with any content widget. It never
|
||||
takes keyboard focus from the main window; a HoverCardController opens and closes it. A
|
||||
non-activating Tool window rather than a ToolTip one, so its buttons take clicks on every
|
||||
platform.
|
||||
|
||||
Args:
|
||||
owner(QWidget): The widget the card belongs to (its parent).
|
||||
content(QWidget | None): The widget shown in the card; can be set later with set_content.
|
||||
width(int | None): Fixed width of the card frame; None follows the content.
|
||||
object_name(str): Object name of the card frame, for its style sheet.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
owner: QWidget,
|
||||
content: QWidget | None = None,
|
||||
width: int | None = None,
|
||||
object_name: str = "status_hover_card",
|
||||
):
|
||||
super().__init__(
|
||||
owner,
|
||||
Qt.WindowType.Tool
|
||||
| Qt.WindowType.FramelessWindowHint
|
||||
| Qt.WindowType.WindowDoesNotAcceptFocus
|
||||
# the card draws its own rounded shadow; the native one (macOS) is computed for the
|
||||
# whole translucent window and shows as a square-cornered band around the card
|
||||
| Qt.WindowType.NoDropShadowWindowHint,
|
||||
)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
|
||||
outer = self.outer_layout = QVBoxLayout(self)
|
||||
outer.setContentsMargins(12, 12, 12, 12) # room for the shadow
|
||||
self.card = QFrame(self)
|
||||
self.card.setObjectName(object_name)
|
||||
if width is not None:
|
||||
self.card.setFixedWidth(width)
|
||||
shadow = QGraphicsDropShadowEffect(self.card)
|
||||
shadow.setBlurRadius(24)
|
||||
shadow.setOffset(0, 4)
|
||||
shadow.setColor(QColor(0, 0, 0, 70))
|
||||
self.card.setGraphicsEffect(shadow)
|
||||
self.inner_layout = QVBoxLayout(self.card)
|
||||
self.inner_layout.setContentsMargins(14, 14, 14, 14)
|
||||
outer.addWidget(self.card)
|
||||
self.content: QWidget | None = None
|
||||
self.hint: QLabel | None = None
|
||||
if content is not None:
|
||||
self.set_content(content)
|
||||
self.refresh_style()
|
||||
|
||||
def set_content(self, content: QWidget) -> None:
|
||||
"""Show a widget in the card, in place of the previous content."""
|
||||
if self.content is not None:
|
||||
self.inner_layout.removeWidget(self.content)
|
||||
self.content = content
|
||||
content.setParent(self.card)
|
||||
self.inner_layout.insertWidget(0, content)
|
||||
|
||||
def add_hint(self, text: str) -> QLabel:
|
||||
"""Add a small muted line below the content, e.g. how to dock the widget."""
|
||||
if self.hint is None:
|
||||
self.hint = QLabel(self.card)
|
||||
self.hint.setObjectName("status_card_hint")
|
||||
self.inner_layout.addWidget(self.hint)
|
||||
self.refresh_style()
|
||||
self.hint.setText(text)
|
||||
return self.hint
|
||||
|
||||
def refresh_style(self) -> None:
|
||||
"""Re-read the theme colours."""
|
||||
colors = theme_colors()
|
||||
self.card.setStyleSheet(
|
||||
f"#{self.card.objectName()} {{ background: {css(colors['card'])};"
|
||||
f" border: 1px solid {css(colors['border'])}; border-radius: 8px; }}"
|
||||
f"#status_card_hint {{ color: {css(colors['muted'])}; font-size: 11px; }}"
|
||||
)
|
||||
|
||||
|
||||
class HoverCardController(QObject):
|
||||
"""
|
||||
Opens a HoverCard above an anchor widget on hover and keeps it open while the cursor is over
|
||||
the anchor, the card, the gap between them or one of the extra widgets, while the anchor has
|
||||
keyboard focus, or while a popup or dialog of the card is open. The card closes GRACE_MS after
|
||||
the cursor has left, on Esc, and when the application is deactivated. It is kept on the
|
||||
screen of the anchor and follows it when either moves or changes size.
|
||||
|
||||
Only a cursor poll decides inside or outside: Enter and Leave events are not reliable while
|
||||
the card window is shown (e.g. on macOS).
|
||||
|
||||
Args:
|
||||
anchor(QWidget): The widget the card opens above; its Enter opens the card.
|
||||
card(HoverCard): The card window.
|
||||
keep_open(Callable[[], bool] | None): Asked on each poll; True keeps the card open.
|
||||
can_open(Callable[[], bool] | None): Asked before opening; False keeps the card closed.
|
||||
on_close(Callable[[], None] | None): Called when the card closes.
|
||||
align(CardAlign): LEFT aligns the card to the anchor's left edge, CENTER centres it on
|
||||
the anchor (for a wide anchor such as the client info label).
|
||||
"""
|
||||
|
||||
GRACE_MS = 250 # how long the cursor may be outside before the card closes
|
||||
POLL_MS = 90 # cursor check while hovered or open
|
||||
HOVER_TOLERANCE = 4 # px around anchor, extras and card that still count as inside
|
||||
GAP = 8 # px between the anchor and the card
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
anchor: QWidget,
|
||||
card: HoverCard,
|
||||
keep_open: Callable[[], bool] | None = None,
|
||||
can_open: Callable[[], bool] | None = None,
|
||||
on_close: Callable[[], None] | None = None,
|
||||
align: CardAlign | str = CardAlign.LEFT,
|
||||
):
|
||||
super().__init__(anchor)
|
||||
self.anchor = anchor
|
||||
self.card = card
|
||||
self.align = CardAlign(align)
|
||||
self._keep_open = keep_open
|
||||
self._can_open = can_open
|
||||
self._on_close = on_close
|
||||
self._extras: list[QWidget] = []
|
||||
self._outside_since: float | None = None
|
||||
self.poll = QTimer(self)
|
||||
self.poll.setInterval(self.POLL_MS)
|
||||
self.poll.timeout.connect(self.check_cursor)
|
||||
for widget in (anchor, card):
|
||||
widget.installEventFilter(self)
|
||||
app = QGuiApplication.instance()
|
||||
self._app_connected = app is not None
|
||||
if app is not None:
|
||||
app.applicationStateChanged.connect(self._on_application_state)
|
||||
|
||||
@property
|
||||
def outside_since(self) -> float | None:
|
||||
"""time.monotonic() when the cursor left, or None while it is inside."""
|
||||
return self._outside_since
|
||||
|
||||
def add_extra(self, widget: QWidget) -> None:
|
||||
"""Count a widget next to the anchor as inside, e.g. a Stop button; it does not open it."""
|
||||
self._extras.append(widget)
|
||||
widget.installEventFilter(self)
|
||||
|
||||
def start_watching(self) -> None:
|
||||
"""Start the cursor poll; repeated (sometimes synthetic) Enter events do not restart it."""
|
||||
if not self.poll.isActive():
|
||||
self._outside_since = None
|
||||
self.poll.start()
|
||||
|
||||
def open(self) -> None:
|
||||
"""Show the card above the anchor."""
|
||||
if self._can_open is not None and not self._can_open():
|
||||
return
|
||||
self.start_watching()
|
||||
if self.card.isVisible():
|
||||
return
|
||||
self.card.refresh_style() # the theme may have changed while it was closed
|
||||
self.card.adjustSize()
|
||||
self.place()
|
||||
self.card.show()
|
||||
|
||||
def close(self) -> None:
|
||||
"""Hide the card and stop watching the cursor."""
|
||||
if self._on_close is not None:
|
||||
self._on_close()
|
||||
self.leave()
|
||||
|
||||
def leave(self) -> None:
|
||||
"""Hide the card without the on_close hook (the cursor left)."""
|
||||
self.poll.stop()
|
||||
self._outside_since = None
|
||||
self.card.hide()
|
||||
set_hovered = getattr(self.anchor, "set_hovered", None)
|
||||
if callable(set_hovered):
|
||||
set_hovered(False)
|
||||
|
||||
def place(self) -> None:
|
||||
"""
|
||||
Put the card above the anchor, left-aligned to it (or centred), with its bottom at the
|
||||
anchor, and keep it inside the available geometry of the anchor's screen.
|
||||
"""
|
||||
margin = self.card.outer_layout.contentsMargins()
|
||||
top_left = self.anchor.mapToGlobal(QPoint(0, 0))
|
||||
if self.align == CardAlign.CENTER:
|
||||
x = top_left.x() + (self.anchor.width() - self.card.width()) // 2
|
||||
else:
|
||||
x = top_left.x() - margin.left()
|
||||
y = top_left.y() - self.card.height() + margin.bottom() - self.GAP
|
||||
screen = self.anchor.screen() or QGuiApplication.primaryScreen()
|
||||
if screen is not None:
|
||||
area = screen.availableGeometry()
|
||||
x = max(area.left(), min(x, area.right() - self.card.width() + 1))
|
||||
y = max(area.top(), min(y, area.bottom() - self.card.height() + 1))
|
||||
self.card.move(x, y)
|
||||
|
||||
def _global_rect(self, widget: QWidget) -> QRect:
|
||||
rect = QRect(widget.mapToGlobal(QPoint(0, 0)), widget.size())
|
||||
tol = self.HOVER_TOLERANCE
|
||||
return rect.adjusted(-tol, -tol, tol, tol)
|
||||
|
||||
def hovered(self) -> bool:
|
||||
"""Whether the cursor is over the anchor, an extra, the card, or the gap to the card."""
|
||||
pos = QCursor.pos()
|
||||
widgets = [self.anchor, *self._extras]
|
||||
rects = [self._global_rect(w) for w in widgets if w.isVisible()]
|
||||
if self.card.isVisible():
|
||||
card = self._global_rect(self.card.card)
|
||||
anchor = self._global_rect(self.anchor)
|
||||
rects.append(card)
|
||||
rects.append(
|
||||
QRect(anchor.left(), card.bottom(), anchor.width(), anchor.top() - card.bottom())
|
||||
)
|
||||
return any(rect.contains(pos) for rect in rects)
|
||||
|
||||
def _owns(self, widget: QWidget | None) -> bool:
|
||||
owner = widget.parentWidget() if widget is not None else None
|
||||
if owner is None:
|
||||
return False
|
||||
roots = [self.card, self.anchor, *self._extras]
|
||||
host = self.anchor.parentWidget()
|
||||
if host is not None:
|
||||
roots.append(host)
|
||||
return any(owner is root or root.isAncestorOf(owner) for root in roots)
|
||||
|
||||
def own_window_open(self) -> bool:
|
||||
"""
|
||||
Whether a popup or a modal dialog of the card or the anchor is open, e.g. the arrow menu
|
||||
of a Stop in the card or a confirmation dialog of its content.
|
||||
"""
|
||||
return self._owns(QApplication.activePopupWidget()) or self._owns(
|
||||
QApplication.activeModalWidget()
|
||||
)
|
||||
|
||||
def _anchor_has_keyboard_focus(self) -> bool:
|
||||
return bool(getattr(self.anchor, "keyboard_focus", False))
|
||||
|
||||
@SafeSlot()
|
||||
def check_cursor(self) -> None:
|
||||
"""The poll: close the card GRACE_MS after the cursor has left."""
|
||||
if self.hovered() or self._anchor_has_keyboard_focus() or self.own_window_open():
|
||||
self._outside_since = None
|
||||
return
|
||||
if self._keep_open is not None and self._keep_open():
|
||||
return
|
||||
now = time.monotonic()
|
||||
if self._outside_since is None:
|
||||
self._outside_since = now
|
||||
elif now - self._outside_since >= self.GRACE_MS / 1000:
|
||||
self.leave()
|
||||
|
||||
@SafeSlot(object)
|
||||
def _on_application_state(self, state) -> None:
|
||||
if state != Qt.ApplicationState.ApplicationActive:
|
||||
self.close()
|
||||
|
||||
def eventFilter(self, obj, event): # pylint: disable=invalid-name
|
||||
kind = event.type()
|
||||
if kind == QEvent.Type.Enter and obj is self.anchor:
|
||||
set_hovered = getattr(self.anchor, "set_hovered", None)
|
||||
if callable(set_hovered):
|
||||
set_hovered(True)
|
||||
self.open()
|
||||
elif kind == QEvent.Type.Enter and obj is self.card:
|
||||
self.open()
|
||||
elif kind == QEvent.Type.Enter and obj in self._extras:
|
||||
self.start_watching()
|
||||
elif kind == QEvent.Type.Leave and obj is self.anchor and not self.card.isVisible():
|
||||
set_hovered = getattr(self.anchor, "set_hovered", None)
|
||||
if callable(set_hovered):
|
||||
set_hovered(False)
|
||||
elif (
|
||||
kind == QEvent.Type.FocusIn
|
||||
and obj is self.anchor
|
||||
and event.reason() in KEYBOARD_FOCUS_REASONS
|
||||
):
|
||||
self.open()
|
||||
elif kind == QEvent.Type.KeyPress and event.key() == Qt.Key.Key_Escape:
|
||||
self.close()
|
||||
return True
|
||||
elif kind in (QEvent.Type.Move, QEvent.Type.Resize) and self.card.isVisible():
|
||||
# the card grows with its content, and the anchor moves when a widget next to it
|
||||
# slides in: keep the card bottom-anchored above the anchor
|
||||
if obj is self.anchor or obj is self.card:
|
||||
self.place()
|
||||
return super().eventFilter(obj, event)
|
||||
|
||||
def anchor_window_deactivated(self) -> None:
|
||||
"""Close unless the card itself or one of its popups or dialogs took the activation."""
|
||||
if not self.card.isActiveWindow() and not self.own_window_open():
|
||||
self.close()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""Stop the poll, close the card and disconnect from the application."""
|
||||
self.poll.stop()
|
||||
app = QGuiApplication.instance()
|
||||
if app is not None and self._app_connected:
|
||||
self._app_connected = False
|
||||
try:
|
||||
app.applicationStateChanged.disconnect(self._on_application_state)
|
||||
except (TypeError, RuntimeError):
|
||||
pass
|
||||
self.card.hide()
|
||||
|
||||
|
||||
class StatusPillItem(BECWidget, QWidget):
|
||||
"""
|
||||
A status-bar pill with a badge chip and optional widgets next to it, and a card with the full
|
||||
|
||||
@@ -23,6 +23,7 @@ import bec_widgets
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.colors import apply_theme
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.utils.hover_card import CardAlign, HoverCard, HoverCardController
|
||||
from bec_widgets.utils.ui_loader import UILoader
|
||||
from bec_widgets.widgets.containers.dock_area.profile_utils import (
|
||||
is_experimental_features_enabled,
|
||||
@@ -35,12 +36,7 @@ from bec_widgets.widgets.containers.main_window.addons.notification_center.notif
|
||||
)
|
||||
from bec_widgets.widgets.containers.main_window.addons.scan_status_item import ScanStatusItem
|
||||
from bec_widgets.widgets.containers.main_window.addons.scroll_label import ScrollLabel
|
||||
from bec_widgets.widgets.containers.main_window.addons.status_pill import (
|
||||
CardAlign,
|
||||
HoverCard,
|
||||
HoverCardController,
|
||||
StatusPillItem,
|
||||
)
|
||||
from bec_widgets.widgets.containers.main_window.addons.status_pill import StatusPillItem
|
||||
from bec_widgets.widgets.containers.main_window.addons.web_links import BECWebLinksMixin
|
||||
from bec_widgets.widgets.utility.feedback_dialog.feedback_dialog import FeedbackDialog
|
||||
from bec_widgets.widgets.utility.widget_hierarchy_tree.widget_hierarchy_tree import (
|
||||
|
||||
@@ -9,10 +9,10 @@ from qtpy.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout, QWidget
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.colors import Colors
|
||||
from bec_widgets.utils.error_popups import SafeProperty
|
||||
from bec_widgets.utils.hover_card import HoverCard
|
||||
from bec_widgets.utils.settings_dialog import SettingsDialog
|
||||
from bec_widgets.utils.toolbars.actions import MaterialIconAction
|
||||
from bec_widgets.utils.toolbars.toolbar import ModularToolBar
|
||||
from bec_widgets.widgets.containers.main_window.addons.hover_widget import WidgetTooltip
|
||||
from bec_widgets.widgets.progress.ring_progress_bar.ring import Ring
|
||||
from bec_widgets.widgets.progress.ring_progress_bar.ring_progress_settings_cards import RingSettings
|
||||
|
||||
@@ -37,7 +37,10 @@ class RingProgressContainerWidget(QWidget):
|
||||
self._hover_tooltip_label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
self._hover_tooltip_label.setMaximumWidth(260)
|
||||
self._hover_tooltip_label.setStyleSheet("font-size: 12px;")
|
||||
self._hover_tooltip = WidgetTooltip(self._hover_tooltip_label)
|
||||
self._hover_tooltip = HoverCard(
|
||||
self, self._hover_tooltip_label, object_name="ring_hover_card", hide_on_leave=True
|
||||
)
|
||||
self._hover_tooltip.hide()
|
||||
self.setLayout(QHBoxLayout())
|
||||
self.setMouseTracking(True)
|
||||
self.initialize_bars()
|
||||
@@ -250,7 +253,6 @@ class RingProgressContainerWidget(QWidget):
|
||||
if self._last_hover_global_pos is None:
|
||||
return
|
||||
self._hover_tooltip_label.setText(text)
|
||||
self._hover_tooltip.apply_theme()
|
||||
self._hover_tooltip.show_near(self._last_hover_global_pos)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# pylint: disable=missing-function-docstring, missing-module-docstring
|
||||
import pytest
|
||||
from qtpy.QtCore import QEvent, QPoint
|
||||
from qtpy.QtGui import QGuiApplication
|
||||
from qtpy.QtWidgets import QApplication, QLabel, QWidget
|
||||
|
||||
from bec_widgets.utils.hover_card import HoverCard
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owner(qtbot):
|
||||
widget = QWidget()
|
||||
qtbot.addWidget(widget)
|
||||
yield widget
|
||||
|
||||
|
||||
def _card(owner, **kwargs):
|
||||
label = QLabel("Some help that explains what this section is for")
|
||||
return HoverCard(owner, label, **kwargs)
|
||||
|
||||
|
||||
def _frame(card):
|
||||
return card.card.geometry().translated(card.pos())
|
||||
|
||||
|
||||
def test_show_near_places_the_frame_below_right_of_the_point(owner):
|
||||
card = _card(owner)
|
||||
area = QGuiApplication.primaryScreen().availableGeometry()
|
||||
point = area.topLeft() + QPoint(50, 50)
|
||||
card.show_near(point)
|
||||
assert card.isVisible()
|
||||
frame = _frame(card)
|
||||
assert (frame.left(), frame.top()) == (point.x() + 12, point.y() + 16)
|
||||
card.hide()
|
||||
|
||||
|
||||
def test_show_near_flips_at_the_screen_edge_and_stays_on_screen(owner):
|
||||
card = _card(owner)
|
||||
area = QGuiApplication.primaryScreen().availableGeometry()
|
||||
corner = area.bottomRight() - QPoint(5, 5)
|
||||
card.show_near(corner)
|
||||
frame = _frame(card)
|
||||
assert frame.right() < corner.x() and frame.bottom() < corner.y() # flipped to up-left
|
||||
assert area.contains(card.geometry())
|
||||
card.hide()
|
||||
|
||||
|
||||
def test_show_near_custom_offset(owner):
|
||||
card = _card(owner)
|
||||
area = QGuiApplication.primaryScreen().availableGeometry()
|
||||
point = area.topLeft() + QPoint(40, 40)
|
||||
card.show_near(point, QPoint(0, 30))
|
||||
frame = _frame(card)
|
||||
assert (frame.left(), frame.top()) == (point.x(), point.y() + 30)
|
||||
card.hide()
|
||||
|
||||
|
||||
def test_hide_on_leave_only_when_asked(owner):
|
||||
area = QGuiApplication.primaryScreen().availableGeometry()
|
||||
sticky, tooltip = _card(owner), _card(owner, hide_on_leave=True)
|
||||
for card in (sticky, tooltip):
|
||||
card.show_near(area.topLeft() + QPoint(30, 30))
|
||||
QApplication.sendEvent(card, QEvent(QEvent.Type.Leave))
|
||||
assert sticky.isVisible() # the status bar cards close through their controller
|
||||
assert not tooltip.isVisible()
|
||||
sticky.hide()
|
||||
@@ -720,3 +720,24 @@ def test_ide_explorer_refresh_macro_file_no_sections(ide_explorer, qtbot):
|
||||
# Should handle gracefully without error
|
||||
ide_explorer.refresh_macro_file("/some/path/test.py")
|
||||
# Test passes if no exception is raised
|
||||
|
||||
|
||||
def test_section_help_popup_toggles_and_hides_on_leave(ide_explorer, qtbot):
|
||||
"""The help is a hover card next to the info button: a second click or leaving it hides it."""
|
||||
from qtpy.QtCore import QEvent
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
from bec_widgets.utils.hover_card import HoverCard
|
||||
|
||||
section = ide_explorer.main_explorer.get_section("SCRIPTS")
|
||||
section.header_info_button.click()
|
||||
card = section._help_tooltip
|
||||
assert isinstance(card, HoverCard) and card.parent() is section
|
||||
qtbot.waitUntil(card.isVisible, timeout=1000)
|
||||
section.header_info_button.click()
|
||||
assert not card.isVisible()
|
||||
section.header_info_button.click()
|
||||
assert card.isVisible()
|
||||
QApplication.sendEvent(card, QEvent(QEvent.Type.Leave))
|
||||
assert not card.isVisible()
|
||||
section._cleanup_help_tooltip()
|
||||
@@ -11,7 +11,6 @@ from qtpy.QtWidgets import QApplication, QFrame, QLabel, QMessageBox
|
||||
from bec_widgets.applications.companion_app import GUIServer
|
||||
from bec_widgets.tests.client_mocks import mocked_client
|
||||
from bec_widgets.widgets.containers.dock_area.profile_utils import SETTINGS_KEYS
|
||||
from bec_widgets.widgets.containers.main_window.addons.hover_widget import WidgetTooltip
|
||||
from bec_widgets.widgets.containers.main_window.addons.scroll_label import ScrollLabel
|
||||
from bec_widgets.widgets.containers.main_window.addons.web_links import BECWebLinksMixin
|
||||
from bec_widgets.widgets.containers.main_window.main_window import BECMainWindow
|
||||
@@ -337,13 +336,13 @@ def test_bec_weblinks(monkeypatch):
|
||||
|
||||
def test_client_info_opens_a_card_with_the_full_message(bec_main_window, qtbot, monkeypatch):
|
||||
"""The scrolling client info shows the full message in a card on hover; empty: no card."""
|
||||
from bec_widgets.widgets.containers.main_window.addons import status_pill
|
||||
from bec_widgets.utils import hover_card
|
||||
|
||||
label = bec_main_window._client_info_label
|
||||
card = bec_main_window._client_info_card
|
||||
hover = bec_main_window._client_info_hover
|
||||
centre = label.mapToGlobal(label.rect().center())
|
||||
monkeypatch.setattr(status_pill.QCursor, "pos", staticmethod(lambda: centre))
|
||||
monkeypatch.setattr(hover_card.QCursor, "pos", staticmethod(lambda: centre))
|
||||
|
||||
hover.open()
|
||||
assert not card.isVisible() # nothing to show yet
|
||||
@@ -358,28 +357,10 @@ def test_client_info_opens_a_card_with_the_full_message(bec_main_window, qtbot,
|
||||
) # centred on the label unless clamped at a screen edge
|
||||
|
||||
far = QPoint(-5000, -5000)
|
||||
monkeypatch.setattr(status_pill.QCursor, "pos", staticmethod(lambda: far))
|
||||
monkeypatch.setattr(hover_card.QCursor, "pos", staticmethod(lambda: far))
|
||||
qtbot.waitUntil(lambda: not card.isVisible(), timeout=2000)
|
||||
|
||||
|
||||
def test_widget_tooltip_show_and_hide(qtbot):
|
||||
"""
|
||||
WidgetTooltip should appear when show_above is called and hide on Leave.
|
||||
"""
|
||||
full_lbl = QLabel("Standalone tooltip content")
|
||||
tooltip = create_widget(qtbot, WidgetTooltip, content=full_lbl)
|
||||
|
||||
# Show above an arbitrary point
|
||||
pos = QPoint(200, 200)
|
||||
tooltip.show_above(pos)
|
||||
assert tooltip.isVisible()
|
||||
|
||||
# Send a synthetic Leave event
|
||||
QApplication.sendEvent(tooltip, QEvent(QEvent.Leave))
|
||||
qtbot.waitUntil(lambda: not tooltip.isVisible(), timeout=500)
|
||||
assert not tooltip.isVisible()
|
||||
|
||||
|
||||
def test_status_bar_holds_several_pills_each_with_its_own_fill(bec_main_window, qtbot, tmp_path):
|
||||
from qtpy.QtCore import QSettings
|
||||
from qtpy.QtWidgets import QLabel
|
||||
|
||||
@@ -799,3 +799,19 @@ def test_set_progress_state_clamps_and_ignores_out_of_range_index(ring_progress_
|
||||
# value above max clamps to 100; out-of-range index is ignored, not an error
|
||||
ring_progress_bar.set_progress_state({0: 150.0, 99: 42.0})
|
||||
assert rings[0].config.value == 100.0
|
||||
|
||||
|
||||
def test_hover_tooltip_is_a_hover_card_next_to_the_cursor(qtbot, container):
|
||||
from bec_widgets.utils.hover_card import HoverCard
|
||||
|
||||
ring = container.add_ring()
|
||||
tooltip = container._hover_tooltip
|
||||
assert isinstance(tooltip, HoverCard) and tooltip.hide_on_leave
|
||||
assert not tooltip.isVisible()
|
||||
container._last_hover_global_pos = QPoint(100, 100)
|
||||
container.refresh_hover_tooltip(ring)
|
||||
assert tooltip.isVisible()
|
||||
assert tooltip.content is container._hover_tooltip_label
|
||||
frame = tooltip.card.geometry().translated(tooltip.pos())
|
||||
assert frame.left() >= 100 and frame.top() >= 100 # below and right of the cursor
|
||||
tooltip.hide()
|
||||
@@ -171,9 +171,9 @@ def test_stop_only_when_stoppable_and_uses_the_shared_stop(item, qtbot):
|
||||
|
||||
|
||||
def _cursor_at(monkeypatch, point):
|
||||
from bec_widgets.widgets.containers.main_window.addons import status_pill
|
||||
from bec_widgets.utils import hover_card
|
||||
|
||||
monkeypatch.setattr(status_pill.QCursor, "pos", staticmethod(lambda: point))
|
||||
monkeypatch.setattr(hover_card.QCursor, "pos", staticmethod(lambda: point))
|
||||
|
||||
|
||||
def test_hover_card_and_outline_clear_without_a_leave_event(item, qtbot, monkeypatch):
|
||||
|
||||
@@ -106,9 +106,9 @@ def test_generic_item_saves_its_choices_under_its_prefix(generic_item, tmp_path)
|
||||
|
||||
|
||||
def _cursor_at(monkeypatch, point):
|
||||
from bec_widgets.widgets.containers.main_window.addons import status_pill
|
||||
from bec_widgets.utils import hover_card
|
||||
|
||||
monkeypatch.setattr(status_pill.QCursor, "pos", staticmethod(lambda: point))
|
||||
monkeypatch.setattr(hover_card.QCursor, "pos", staticmethod(lambda: point))
|
||||
|
||||
|
||||
def _outer_rect(item):
|
||||
@@ -250,3 +250,28 @@ def test_hover_cleanup_can_run_twice(generic_item, recwarn):
|
||||
generic_item.hover.cleanup()
|
||||
generic_item.hover.cleanup()
|
||||
assert not [w for w in recwarn if "Failed to disconnect" in str(w.message)]
|
||||
|
||||
|
||||
def test_late_enter_opens_no_card_for_a_hidden_or_cleaned_up_pill(generic_item, qtbot):
|
||||
from qtpy.QtCore import QPointF
|
||||
from qtpy.QtGui import QEnterEvent
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
item = generic_item
|
||||
|
||||
def enter():
|
||||
point = QPointF(5, 5)
|
||||
QApplication.sendEvent(item.pill, QEnterEvent(point, point, point))
|
||||
|
||||
enter() # Qt can still deliver a queued Enter after the window was hidden or closed
|
||||
assert not item.card.isVisible()
|
||||
|
||||
item.show()
|
||||
qtbot.waitExposed(item)
|
||||
enter()
|
||||
assert item.card.isVisible()
|
||||
item.close_card()
|
||||
|
||||
item.hover.cleanup()
|
||||
enter()
|
||||
assert not item.card.isVisible()
|
||||
Reference in new issue
Block a user