Coverage for graphica/gui/builders/common.py: 97.5%
104 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"""画面の組み立てで共有する定数と小さな部品。main_window からも同じ名前で読める。"""
2import os
3from PySide6.QtCore import QEvent, QObject, QRect, QRectF, Qt, Signal
4from PySide6.QtGui import QColor, QPainter, QPainterPath
5from PySide6.QtWidgets import QComboBox, QStyle, QStyleOptionViewItem, QStyledItemDelegate
6from graphica.core.i18n import tr
7from graphica.gui import theme
8from graphica.gui.dataset_style_icon import DATASET_TREE_NAME_COLUMN
9from graphica.gui.icon_utils import ICONS_DIR, load_svg_icon
10from graphica.gui.mathtext_preview import FitWidthPixmapLabel
11from graphica.gui.resources import resource_path
14# 列番号は dataset_mixin も使うので gui/dataset_style_icon.py にある(循環 import を避けるため)
15DATASET_TREE_VISIBILITY_COLUMN_WIDTH = 26 # 目のアイコン(16px)+クリックの余白
18# ドックの既定の配置を変えたら上げる。保存時の値と違えば保存済みの配置を戻さない
19# (戻すと、新しい既定の配置が既存の利用者に届かない)。
20DOCK_LAYOUT_VERSION = 6
23# データセットのプロパティ欄の節。行は self._prop_form(キー).addRow で足す(番号指定の挿入はしない)。
24DATASET_PROPERTY_SECTIONS = (
25 ('data', 'データ列'),
26 ('style', '基本スタイル'),
27 ('marker', 'マーカー'),
28 ('gradient', 'グラデーション'),
29 ('waterfall', 'ウォーターフォール'),
30 ('map', '2Dマップ・値による配色'),
31 ('extra', '表示の追加要素'),
32 ('place', '配置・情報'),
33)
36# プラグインの種類名は任意の長さなので、コンボの希望幅を固定して省略表示させる
37# (広がると QFormLayout の列幅を通じてドックに横スクロールバーが出る)。
38PLOT_TYPE_COMBO_MIN_CHARS = 11
41def cap_combo_width(combo):
42 """長い項目があっても、コンボの希望幅を種別の欄と同じ文字数にそろえる(項目は開いた一覧で全文が見える)。"""
43 combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
44 combo.setMinimumContentsLength(PLOT_TYPE_COMBO_MIN_CHARS)
47def discard_widget(widget):
48 """組み立ての途中で要らなくなった部品(欄の差し替えの仮の部品・古い入れ物など)を捨てる。
50 deleteLater() はイベントループが回るまで消さず、その間は親の左上に残って下の部品のクリックを
51 横取りする(目盛のフォント・色のボタンが押せなかった)。先に隠しておく。
52 """
53 widget.hide()
54 widget.deleteLater()
57COLORMAP_CHOICES = [
58 'viridis', 'plasma', 'inferno', 'magma', 'cividis',
59 'coolwarm', 'RdBu', 'seismic', 'jet', 'turbo',
60 'gray', 'Blues', 'Greens', 'Reds', 'YlOrRd',
61]
64# Qt 既定の 24px だと、狭いウィンドウでボタンが「>>」に押し込まれて押せない
65TOOLBAR_ICON_SIZE = 18
68def _svg_icon(name, size=20):
69 """テーマの text_secondary 色で描いたアイコン。テーマが変わっても自動では変わらない
71 (常に見えているものは _refresh_custom_svg_icons で作り直す)。
72 """
73 from graphica.gui import theme
74 color = theme.current_tokens()["text_secondary"]
75 return load_svg_icon(resource_path(os.path.join(ICONS_DIR, f"{name}.svg")),
76 color=color, size=size)
79def paint_selection_band(painter, rect):
80 """データセット一覧の選択の帯(1つの角丸)。"""
81 path = QPainterPath()
82 path.addRoundedRect(rect, theme.DATASET_LIST_ITEM_RADIUS, theme.DATASET_LIST_ITEM_RADIUS)
83 painter.fillPath(path, theme.current_accent_soft_qcolor())
86class _DatasetTreeSelectionDelegate(QStyledItemDelegate):
87 """選択の背景を、アイコンの列と文字の列にまたがる1つの角丸で描く。
89 QSS の ::item:selected は2つの列に別々の角丸を描き、間に隙間ができる。背景だけ自前で塗り、
90 State_Selected を外してから標準の描画に任せる。
91 """
93 def paint(self, painter, option, index):
94 opt = QStyleOptionViewItem(option)
95 self.initStyleOption(opt, index)
97 # 選択の帯が滑っている間は、帯は一覧(DatasetTreeWidget.paintEvent)が描く
98 sliding = getattr(opt.widget, 'sliding_selection_band', None) is not None
99 if opt.state & QStyle.StateFlag.State_Selected and sliding:
100 opt.state &= ~QStyle.StateFlag.State_Selected
101 if opt.state & QStyle.StateFlag.State_Selected:
102 painter.save()
103 painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
104 # どの列も行の全幅の角丸を描き、自分の列の中だけに切り取る。列ごとの矩形で塗ると
105 # 半透明の塗りが重なったり角丸が2つに割れたりする。左端は展開矢印の字下げも含める
106 clip = QRect(opt.rect)
107 if index.column() == 0:
108 clip.setLeft(0)
109 painter.setClipRect(clip)
110 rect = QRectF(opt.rect)
111 rect.setLeft(0)
112 if opt.widget is not None:
113 rect.setRight(opt.widget.viewport().width() - 1)
114 paint_selection_band(painter, rect)
115 painter.restore()
116 # 標準の選択の背景を重ねないよう落とす(文字とアイコンの色は選択で変わらない)
117 opt.state &= ~QStyle.StateFlag.State_Selected
119 count_text = _point_count_text(index)
120 if not count_text:
121 super().paint(painter, opt, index)
122 return
123 # 右端に点の数を出す。名前はその手前で省略されるよう、文字の幅を縮めてから描く
124 full_rect = QRect(opt.rect)
125 count_width = opt.fontMetrics.horizontalAdvance(count_text) + DATASET_TREE_COUNT_PADDING
126 opt.rect = full_rect.adjusted(0, 0, -count_width, 0)
127 super().paint(painter, opt, index)
128 painter.save()
129 painter.setPen(QColor(theme.current_tokens()["text_muted"]))
130 painter.drawText(full_rect.adjusted(0, 0, -DATASET_TREE_COUNT_PADDING // 2, 0),
131 int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter), count_text)
132 painter.restore()
134 def sizeHint(self, option, index):
135 hint = super().sizeHint(option, index)
136 hint.setHeight(max(hint.height(), DATASET_TREE_ROW_HEIGHT))
137 return hint
140# 一覧の行の高さと、右端の点の数の余白(見本 docs/dev/mockups/gui_redesign/ の 38px から行の間の分を引いた高さ)
141DATASET_TREE_ROW_HEIGHT = 34
142DATASET_TREE_COUNT_PADDING = 12
145def _point_count_text(index):
146 """データセットの行なら「41 点」(除外した行は数えない)。フォルダや目の列は空。"""
147 if index.column() != DATASET_TREE_NAME_COLUMN:
148 return ""
149 dataset = index.data(Qt.ItemDataRole.UserRole)
150 if dataset is None:
151 return ""
152 try:
153 count = len(dataset.df) - len(getattr(dataset, "masked_row_indices", ()) or ())
154 except TypeError:
155 return ""
156 return f"{max(count, 0)} {tr('点')}"
159class _IgnoreWheelFilter(QObject):
160 def eventFilter(self, watched, event):
161 return event.type() == QEvent.Type.Wheel
164def disable_wheel_tab_switching(tab_widget):
165 """ホイールでタブが切り替わらないようにする。
167 タブバーは QTabWidget が C++ 側で作るので、wheelEvent をクラスごと書き換えても効かない。
168 """
169 tab_bar = tab_widget.tabBar()
170 tab_bar.installEventFilter(_IgnoreWheelFilter(tab_bar))
173class _ClickableMathPreviewLabel(FitWidthPixmapLabel):
174 """タイトルと軸ラベルの欄。mathtext を描いたプレビューで、クリックで編集ダイアログを開く。
176 値は隠した元の QLineEdit が持つ(textChanged もそちらから出る)。
177 """
179 clicked = Signal()
181 def __init__(self, parent=None):
182 super().__init__(parent)
183 self.setObjectName("mathtext_preview_label")
184 self.setCursor(Qt.CursorShape.PointingHandCursor)
185 self.setMinimumHeight(28)
186 self.setToolTip(tr("クリックして編集"))
187 # QLabel は既定でホバーを追跡せず、QSS の :hover が効かない
188 self.setAttribute(Qt.WidgetAttribute.WA_Hover, True)
190 def mousePressEvent(self, event):
191 if event.button() == Qt.MouseButton.LeftButton: 191 ↛ 193line 191 didn't jump to line 193 because the condition on line 191 was always true
192 self.clicked.emit()
193 super().mousePressEvent(event)
196def _insert_form_row_after(form, anchor, *row):
197 """form の anchor(ラベルか欄)の行の次に入れる。行番号で入れると、ほかの挿入の順番が変わったときに黙って別の位置に入る。"""
198 anchor_row, _ = form.getWidgetPosition(anchor)
199 if anchor_row < 0:
200 raise ValueError(f"{anchor!r} は {form.objectName()} にありません")
201 form.insertRow(anchor_row + 1, *row)