"""
collapsible_group_box
チェックボックスで折りたたみ可能な QGroupBox
"""
from PySide6.QtGui import QShowEvent
from PySide6.QtWidgets import QGroupBox, QLayout, QWidget
class CollapsibleGroupBox(QGroupBox):
"""タイトルのチェックで中身を折りたたみできる QGroupBox"""
def __init__(self, title: str) -> None:
super().__init__(title)
self.setCheckable(True)
self.setChecked(False)
self._first_show: bool = True
self.toggled.connect(self._toggle_content)
def showEvent(self, event: QShowEvent) -> None:
"""初回表示時に折りたたみ状態を反映する"""
super().showEvent(event)
if self._first_show:
self._first_show = False
if not self.isChecked():
self._toggle_content(False)
def _toggle_content(self, on: bool) -> None:
"""チェック状態に応じてレイアウト内の要素を表示/非表示する
Args:
on: True で展開,False で折りたたみ
"""
layout = self.layout()
if layout is None:
return
_set_layout_visible(layout, on)
def _set_layout_visible(
layout: QLayout, visible: bool,
) -> None:
"""レイアウト内の全ウィジェットを再帰的に表示/非表示する
Args:
layout: 対象レイアウト
visible: True で表示,False で非表示
"""
for i in range(layout.count()):
item = layout.itemAt(i)
widget = item.widget()
if isinstance(widget, QWidget):
widget.setVisible(visible)
sub = item.layout()
if sub is not None:
_set_layout_visible(sub, visible)