Coverage for graphica/gui/widgets/segmented.py: 90.2%

210 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-25 19:22 +0000

1"""セグメント(横に並んだ排他のボタン)と、今のコンボを値の持ち主にしたままの同期。""" 

2from PySide6.QtCore import QPointF, QRectF, QSize, Qt, Signal 

3from PySide6.QtGui import QColor, QPainter, QPen 

4from PySide6.QtWidgets import QButtonGroup, QFrame, QHBoxLayout, QSizePolicy, QToolButton 

5 

6from graphica.gui import motion, theme 

7 

8# matplotlib の線の種類と、それを描く Qt のペン 

9LINE_STYLE_PENS = { 

10 "-": Qt.PenStyle.SolidLine, 

11 "solid": Qt.PenStyle.SolidLine, 

12 "--": Qt.PenStyle.DashLine, 

13 "dashed": Qt.PenStyle.DashLine, 

14 ":": Qt.PenStyle.DotLine, 

15 "dotted": Qt.PenStyle.DotLine, 

16 "-.": Qt.PenStyle.DashDotLine, 

17 "dashdot": Qt.PenStyle.DashDotLine, 

18} 

19 

20 

21SEGMENT_HEIGHT = 28 

22# 溝の内側の余白と、板どうしの間。板の角丸は QSS の border-radius(溝の丸み 14 から余白を引いた値) 

23SEGMENT_TRACK_PADDING = 2 

24SEGMENT_RADIUS = 11 

25SEGMENT_SHADOW_ALPHA = 36 

26 

27 

28class _LineSegmentButton(QToolButton): 

29 """文字の代わりに線の見本を描く。色は描くたびにトークンから取るので、テーマを替えても描き直すだけでよい。""" 

30 

31 def __init__(self, pen_style, parent=None): 

32 super().__init__(parent) 

33 self._pen_style = pen_style 

34 

35 def sizeHint(self): 

36 return QSize(40, 24) 

37 

38 def minimumSizeHint(self): 

39 # 線の見本は縮めても見分けられるので、狭い欄(グリッドの行)では詰める 

40 return QSize(28, 20) 

41 

42 def paintEvent(self, event): 

43 super().paintEvent(event) 

44 painter = QPainter(self) 

45 painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) 

46 tokens = theme.current_tokens() 

47 if not self.isEnabled(): 

48 color = tokens["text_muted"] 

49 else: 

50 color = tokens["accent_fg"] if self.isChecked() else tokens["text_secondary"] 

51 pen = QPen(QColor(color)) 

52 pen.setWidthF(2.0) 

53 pen.setStyle(self._pen_style) 

54 pen.setCapStyle(Qt.PenCapStyle.FlatCap) 

55 painter.setPen(pen) 

56 y = self.height() / 2 

57 half = min(15.0, self.width() / 2 - 5) 

58 center = self.width() / 2 

59 painter.drawLine(QPointF(center - half, y), QPointF(center + half, y)) 

60 painter.end() 

61 

62 

63class _FillSegmentButton(QToolButton): 

64 """マーカーの塗りの見本(塗った丸か白抜きの丸)。小さいと見分けにくいので、文字より少し大きく描く。""" 

65 

66 DIAMETER = 13.0 

67 

68 def __init__(self, filled, parent=None): 

69 super().__init__(parent) 

70 self._filled = filled 

71 

72 def sizeHint(self): 

73 return QSize(40, 24) 

74 

75 def paintEvent(self, event): 

76 super().paintEvent(event) 

77 tokens = theme.current_tokens() 

78 if not self.isEnabled(): 

79 color = QColor(tokens["text_muted"]) 

80 else: 

81 color = QColor(tokens["accent_fg"] if self.isChecked() else tokens["text_secondary"]) 

82 painter = QPainter(self) 

83 painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) 

84 pen = QPen(color) 

85 pen.setWidthF(1.6) 

86 painter.setPen(pen) 

87 painter.setBrush(color if self._filled else Qt.BrushStyle.NoBrush) 

88 radius = self.DIAMETER / 2 - (0 if self._filled else 0.8) 

89 painter.drawEllipse(QPointF(self.width() / 2, self.height() / 2), radius, radius) 

90 painter.end() 

91 

92 

93class SegmentedControl(QFrame): 

94 """QComboBox と同じ呼び方(currentIndex・itemData・findData・setCurrentIndex)ができる排他のボタンの列。""" 

95 

96 currentIndexChanged = Signal(int) 

97 

98 def __init__(self, parent=None): 

99 super().__init__(parent) 

100 self.setObjectName("segmented_control") 

101 self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) 

102 self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) 

103 # 溝と板の色は QSS。板の位置(segmentPosition)は QSS の見分けに残しておく 

104 self.setFixedHeight(SEGMENT_HEIGHT) 

105 layout = QHBoxLayout(self) 

106 layout.setContentsMargins(SEGMENT_TRACK_PADDING, SEGMENT_TRACK_PADDING, 

107 SEGMENT_TRACK_PADDING, SEGMENT_TRACK_PADDING) 

108 layout.setSpacing(SEGMENT_TRACK_PADDING) 

109 self._group = QButtonGroup(self) 

110 self._group.setExclusive(True) 

111 self._group.idClicked.connect(self.setCurrentIndex) 

112 self._items = [] # (text, data) 

113 self._current = -1 

114 # 板が滑っている途中の位置(止まっているときは選んだボタンの位置に描く) 

115 self._sliding_plate = None 

116 

117 def _add_button(self, button, text, data, tooltip): 

118 button.setObjectName("segment") 

119 button.setCheckable(True) 

120 button.setFocusPolicy(Qt.FocusPolicy.NoFocus) 

121 button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) 

122 button.setCursor(Qt.CursorShape.PointingHandCursor) 

123 if tooltip: 

124 button.setToolTip(tooltip) 

125 index = len(self._items) 

126 self._items.append((text, data)) 

127 self._group.addButton(button, index) 

128 self.layout().addWidget(button) 

129 self._refresh_positions() 

130 if self._current < 0: 

131 # QComboBox と同じく、最初の項目を足した時点でそれを選ぶ 

132 self.setCurrentIndex(0) 

133 return index 

134 

135 def _refresh_positions(self): 

136 buttons = self._group.buttons() 

137 for index, button in enumerate(buttons): 

138 if len(buttons) == 1: 

139 position = "only" 

140 elif index == 0: 

141 position = "first" 

142 elif index == len(buttons) - 1: 

143 position = "last" 

144 else: 

145 position = "middle" 

146 if button.property("segmentPosition") != position: 

147 button.setProperty("segmentPosition", position) 

148 button.style().unpolish(button) 

149 button.style().polish(button) 

150 

151 def addItem(self, text, data=None, tooltip=""): 

152 button = QToolButton(self) 

153 button.setText(text) 

154 button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextOnly) 

155 return self._add_button(button, text, data, tooltip) 

156 

157 def addIconItem(self, icon, data=None, tooltip=""): 

158 button = QToolButton(self) 

159 button.setIcon(icon) 

160 button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonIconOnly) 

161 return self._add_button(button, "", data, tooltip) 

162 

163 def addLineStyleItem(self, line_style, data=None, tooltip=""): 

164 """線の見本のボタン。line_style は matplotlib の書き方('-'・'--'・':'・'-.' など)。""" 

165 button = _LineSegmentButton(LINE_STYLE_PENS[line_style], self) 

166 return self._add_button(button, "", line_style if data is None else data, tooltip) 

167 

168 def addMarkerFillItem(self, filled, data=None, tooltip=""): 

169 """マーカーの塗りの見本のボタン(filled=True で塗った丸、False で白抜きの丸)。""" 

170 return self._add_button(_FillSegmentButton(filled, self), "", data, tooltip) 

171 

172 def setItemEnabled(self, index, enabled): 

173 """コンボの項目を選べなくしたとき(model().item(i).setEnabled)と同じく、そのボタンだけ押せなくする。""" 

174 button = self._group.button(index) 

175 if button is not None: 175 ↛ exitline 175 didn't return from function 'setItemEnabled' because the condition on line 175 was always true

176 button.setEnabled(enabled) 

177 

178 def count(self): 

179 return len(self._items) 

180 

181 def itemText(self, index): 

182 return self._items[index][0] if 0 <= index < len(self._items) else "" 

183 

184 def itemData(self, index): 

185 return self._items[index][1] if 0 <= index < len(self._items) else None 

186 

187 def findData(self, data): 

188 for index, (_, item_data) in enumerate(self._items): 

189 if item_data == data: 

190 return index 

191 return -1 

192 

193 def currentIndex(self): 

194 return self._current 

195 

196 def currentData(self): 

197 return self.itemData(self._current) 

198 

199 def setCurrentIndex(self, index): 

200 if index < -1 or index >= len(self._items) or index == self._current: 

201 return 

202 start = self._plate_rect() 

203 self._current = index 

204 if index >= 0: 

205 self._group.button(index).setChecked(True) 

206 else: 

207 # 何も選ばない(コンボに見本に無い値が入っているとき)。排他を一時外さないとチェックを外せない 

208 self._group.setExclusive(False) 

209 for button in self._group.buttons(): 

210 button.setChecked(False) 

211 self._group.setExclusive(True) 

212 end = self._plate_rect() 

213 if start is not None and end is not None and self.isVisible() and motion.is_enabled(): 

214 # 動きは次の刻みから値を出すので、最初の1枚が行き先に描かれないよう、出発点を先に置く 

215 self._sliding_plate = start 

216 motion.animate_value(self, "_motion_plate", start, end, self._move_plate, self._stop_plate, after_paint=True) 

217 else: 

218 self._stop_plate() 

219 self.update() 

220 self.currentIndexChanged.emit(index) 

221 

222 def _plate_rect(self): 

223 button = self._group.button(self._current) if self._current >= 0 else None 

224 if button is None or not button.isVisible(): 

225 return None 

226 return QRectF(button.geometry()) 

227 

228 def _move_plate(self, rect): 

229 self._sliding_plate = rect 

230 self.update() 

231 

232 def _stop_plate(self): 

233 self._sliding_plate = None 

234 self.update() 

235 

236 def paintEvent(self, event): 

237 """溝(QSS)の上に、選んだものの板とその下の薄い影を描く(文字は子のボタンが上に描く)。""" 

238 super().paintEvent(event) 

239 rect = self._sliding_plate if self._sliding_plate is not None else self._plate_rect() 

240 if rect is None: 

241 return 

242 tokens = theme.current_tokens() 

243 painter = QPainter(self) 

244 painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) 

245 painter.setPen(Qt.PenStyle.NoPen) 

246 if self.isEnabled(): 

247 painter.setBrush(QColor(0, 0, 0, SEGMENT_SHADOW_ALPHA)) 

248 painter.drawRoundedRect(rect.adjusted(0, 0.5, 0, 1.0), SEGMENT_RADIUS, SEGMENT_RADIUS) 

249 painter.setBrush(QColor(tokens["raised"] if self.isEnabled() else tokens["surface"])) 

250 painter.drawRoundedRect(rect, SEGMENT_RADIUS, SEGMENT_RADIUS) 

251 painter.end() 

252 

253 def keyPressEvent(self, event): 

254 step = {Qt.Key.Key_Left: -1, Qt.Key.Key_Up: -1, Qt.Key.Key_Right: 1, Qt.Key.Key_Down: 1}.get(event.key()) 

255 if step is None or not self._items: 255 ↛ 256line 255 didn't jump to line 256 because the condition on line 255 was never true

256 super().keyPressEvent(event) 

257 return 

258 self.setCurrentIndex(max(0, min(len(self._items) - 1, self._current + step))) 

259 

260 

261class ComboMirror: 

262 """今のコンボを値の持ち主にしたまま、見た目の代わり(セグメントなど)と同期する。 

263 

264 見た目の側で選ぶとコンボの setCurrentIndex を呼ぶ(コンボのシグナルで今までどおり値が反映される)。 

265 コンボがシグナルを止めて書き換えられる(バインディングの「戻す」)と同期の知らせが来ないので、 

266 戻したあとに refresh() を呼ぶこと。コンボの値は itemData、無ければ表示の文字で突き合わせる。 

267 """ 

268 

269 def __init__(self, view, combo): 

270 self.view = view 

271 self.combo = combo 

272 combo.currentIndexChanged.connect(lambda _index: self.refresh()) 

273 view.currentIndexChanged.connect(self._on_view_changed) 

274 self.refresh() 

275 

276 def _combo_key(self, index): 

277 data = self.combo.itemData(index) 

278 return self.combo.itemText(index) if data is None else data 

279 

280 def refresh(self): 

281 index = self.view.findData(self._combo_key(self.combo.currentIndex())) 

282 blocked = self.view.blockSignals(True) 

283 self.view.setCurrentIndex(index) 

284 self.view.blockSignals(blocked) 

285 

286 def _on_view_changed(self, index): 

287 key = self.view.itemData(index) 

288 combo_index = self.combo.findData(key) 

289 if combo_index < 0 and isinstance(key, str): 

290 combo_index = self.combo.findText(key) 

291 if combo_index >= 0 and combo_index != self.combo.currentIndex(): 291 ↛ exitline 291 didn't return from function '_on_view_changed' because the condition on line 291 was always true

292 self.combo.setCurrentIndex(combo_index)