From b66a76f73b41f4b96cbdb8e832a493d42b56e32a Mon Sep 17 00:00:00 2001 From: thankyouverycool <66646555+thankyouverycool@users.noreply.github.com> Date: Sun, 16 Apr 2023 16:03:11 -0400 Subject: [PATCH] LibGUI: Allow SpinBox to set its value with return key Previously SpinBox did not update on return or changes to the editor. The widget had to lose focus or be manually incremented. This lets the editor update on return and now always displays the most recent clamped value. set_value_from_current_text() will also be useful to programmatically set SpinBox within layouts whose default buttons consume return key presses. --- Userland/Libraries/LibGUI/SpinBox.cpp | 18 ++++++++++++------ Userland/Libraries/LibGUI/SpinBox.h | 1 + 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/Userland/Libraries/LibGUI/SpinBox.cpp b/Userland/Libraries/LibGUI/SpinBox.cpp index eda77472f8..362d174ea3 100644 --- a/Userland/Libraries/LibGUI/SpinBox.cpp +++ b/Userland/Libraries/LibGUI/SpinBox.cpp @@ -29,11 +29,7 @@ SpinBox::SpinBox() m_editor->do_delete(); }; m_editor->on_focusout = [this] { - auto value = m_editor->text().to_int(); - if (value.has_value()) - set_value(value.value()); - else - set_value(min()); + set_value_from_current_text(); }; m_editor->on_up_pressed = [this] { set_value(m_value + 1); @@ -42,6 +38,7 @@ SpinBox::SpinBox() set_value(m_value - 1); }; m_editor->on_return_pressed = [this] { + set_value_from_current_text(); if (on_return_pressed) on_return_pressed(); }; @@ -66,6 +63,7 @@ SpinBox::SpinBox() void SpinBox::set_value(int value, AllowCallback allow_callback) { value = clamp(value, m_min, m_max); + m_editor->set_text(DeprecatedString::number(value)); if (m_value == value) return; m_value = value; @@ -73,12 +71,20 @@ void SpinBox::set_value(int value, AllowCallback allow_callback) m_increment_button->set_enabled(m_value < m_max); m_decrement_button->set_enabled(m_value > m_min); - m_editor->set_text(DeprecatedString::number(value)); update(); if (on_change && allow_callback == AllowCallback::Yes) on_change(value); } +void SpinBox::set_value_from_current_text() +{ + auto value = m_editor->text().to_int(); + if (value.has_value()) + set_value(value.value()); + else + set_value(min()); +} + void SpinBox::set_range(int min, int max, AllowCallback allow_callback) { VERIFY(min <= max); diff --git a/Userland/Libraries/LibGUI/SpinBox.h b/Userland/Libraries/LibGUI/SpinBox.h index 79a3f80125..4679a05276 100644 --- a/Userland/Libraries/LibGUI/SpinBox.h +++ b/Userland/Libraries/LibGUI/SpinBox.h @@ -18,6 +18,7 @@ public: int value() const { return m_value; } void set_value(int, AllowCallback = AllowCallback::Yes); + void set_value_from_current_text(); int min() const { return m_min; } int max() const { return m_max; }