Coverage for graphica/gui/widgets/elided_label.py: 100.0%
32 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-25 19:22 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-25 19:22 +0000
1"""幅に収まらない文字を「…」で省くラベル。データセット名のように長さの決まらない文字で、親の幅を広げない。"""
2from PySide6.QtCore import QEvent, QSize, Qt
3from PySide6.QtWidgets import QLabel, QSizePolicy
6class ElidedLabel(QLabel):
7 """text() は省く前の全文を返す(翻訳・テスト・記録はそのまま使える)。省いたときだけ全文をツールチップに出す。"""
9 def __init__(self, text="", parent=None):
10 super().__init__(parent)
11 self._full_text = ""
12 # 余裕があれば全文の幅、足りなければ 0 まで縮む(最小の幅は minimumSizeHint で主張しない)
13 self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Preferred)
14 self.setText(text)
16 def setText(self, text):
17 self._full_text = text or ""
18 self._elide()
20 def text(self):
21 return self._full_text
23 def sizeHint(self):
24 hint = super().sizeHint()
25 margins = self.contentsMargins()
26 width = self.fontMetrics().horizontalAdvance(self._full_text) + margins.left() + margins.right() + 2
27 return QSize(width, hint.height())
29 def minimumSizeHint(self):
30 return QSize(0, super().minimumSizeHint().height())
32 def resizeEvent(self, event):
33 super().resizeEvent(event)
34 self._elide()
36 def changeEvent(self, event):
37 super().changeEvent(event)
38 # QSS で太字・大きさが変わると、同じ幅に入る文字数が変わる
39 if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange):
40 self._elide()
42 def _elide(self):
43 width = self.contentsRect().width()
44 shown = self._full_text if width <= 0 else self.fontMetrics().elidedText(
45 self._full_text, Qt.TextElideMode.ElideRight, width)
46 super().setText(shown)
47 super().setToolTip(self._full_text if shown != self._full_text else "")