From 3df7f497062214e78125b278705d72ebd505313b Mon Sep 17 00:00:00 2001 From: Pam <54282105+ppwadhwa@users.noreply.github.com> Date: Sun, 27 Nov 2022 19:43:05 -0600 Subject: [PATCH] Add signal to QCollapsible (#142) * add signal when toggle button is clicked * emit signal when expand/collapse are called. emit bool. add to test. * fix signal emission Co-authored-by: Talley Lambert --- src/superqt/collapsible/_collapsible.py | 16 +++++++++++++++- tests/test_collapsible.py | 15 ++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/superqt/collapsible/_collapsible.py b/src/superqt/collapsible/_collapsible.py index 37b47b9..953ace2 100644 --- a/src/superqt/collapsible/_collapsible.py +++ b/src/superqt/collapsible/_collapsible.py @@ -1,19 +1,31 @@ """A collapsible widget to hide and unhide child widgets""" from typing import Optional -from qtpy.QtCore import QEasingCurve, QEvent, QMargins, QObject, QPropertyAnimation, Qt +from qtpy.QtCore import ( + QEasingCurve, + QEvent, + QMargins, + QObject, + QPropertyAnimation, + Qt, + Signal, +) from qtpy.QtWidgets import QFrame, QPushButton, QVBoxLayout, QWidget class QCollapsible(QFrame): """A collapsible widget to hide and unhide child widgets. + A signal is emitted when the widget is expanded (True) or collapsed (False). + Based on https://stackoverflow.com/a/68141638 """ _EXPANDED = "▼ " _COLLAPSED = "▲ " + toggled = Signal(bool) + def __init__(self, title: str = "", parent: Optional[QWidget] = None): super().__init__(parent) self._locked = False @@ -123,6 +135,8 @@ class QCollapsible(QFrame): else: self._content.setMaximumHeight(_content_height if forward else 0) + self.toggled.emit(direction == QPropertyAnimation.Direction.Forward) + def _toggle(self): self.expand() if self.isExpanded() else self.collapse() diff --git a/tests/test_collapsible.py b/tests/test_collapsible.py index e4fe89a..b73e8d7 100644 --- a/tests/test_collapsible.py +++ b/tests/test_collapsible.py @@ -1,6 +1,6 @@ """A test module for testing collapsible""" -from qtpy.QtCore import QEasingCurve +from qtpy.QtCore import QEasingCurve, Qt from qtpy.QtWidgets import QPushButton from superqt import QCollapsible @@ -85,3 +85,16 @@ def test_changing_text(qtbot): wdg.setText("Hi new text") assert wdg.text() == "Hi new text" assert wdg._toggle_btn.text() == QCollapsible._COLLAPSED + "Hi new text" + + +def test_toggle_signal(qtbot): + """Test that signal is emitted when widget expanded/collapsed.""" + wdg = QCollapsible() + with qtbot.waitSignal(wdg.toggled, timeout=500): + qtbot.mouseClick(wdg._toggle_btn, Qt.LeftButton) + + with qtbot.waitSignal(wdg.toggled, timeout=500): + wdg.expand() + + with qtbot.waitSignal(wdg.toggled, timeout=500): + wdg.collapse()