GSpinBox.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <LibGUI/GSpinBox.h>
  2. #include <LibGUI/GButton.h>
  3. #include <LibGUI/GTextEditor.h>
  4. GSpinBox::GSpinBox(GWidget* parent)
  5. : GWidget(parent)
  6. {
  7. m_editor = new GTextEditor(GTextEditor::Type::SingleLine, this);
  8. m_editor->on_change = [this] {
  9. bool ok;
  10. int value = m_editor->text().to_uint(ok);
  11. if (ok)
  12. set_value(value);
  13. else
  14. m_editor->set_text(String::format("%d", m_value));
  15. };
  16. m_increment_button = new GButton(this);
  17. m_increment_button->set_caption("\xf6");
  18. m_increment_button->on_click = [this] (GButton&) { set_value(m_value + 1); };
  19. m_decrement_button = new GButton(this);
  20. m_decrement_button->set_caption("\xf7");
  21. m_decrement_button->on_click = [this] (GButton&) { set_value(m_value - 1); };
  22. }
  23. GSpinBox::~GSpinBox()
  24. {
  25. }
  26. void GSpinBox::set_value(int value)
  27. {
  28. if (value < m_min)
  29. value = m_min;
  30. if (value > m_max)
  31. value = m_max;
  32. if (m_value == value)
  33. return;
  34. m_value = value;
  35. m_editor->set_text(String::format("%d", value));
  36. update();
  37. if (on_change)
  38. on_change(value);
  39. }
  40. void GSpinBox::set_range(int min, int max)
  41. {
  42. ASSERT(min <= max);
  43. if (m_min == min && m_max == max)
  44. return;
  45. m_min = min;
  46. m_max = max;
  47. int old_value = m_value;
  48. if (m_value < m_min)
  49. m_value = m_min;
  50. if (m_value > m_max)
  51. m_value = m_max;
  52. if (on_change && m_value != old_value)
  53. on_change(m_value);
  54. update();
  55. }
  56. void GSpinBox::resize_event(GResizeEvent& event)
  57. {
  58. int frame_thickness = m_editor->frame_thickness();
  59. int button_height = (event.size().height() / 2) - frame_thickness;
  60. int button_width = 15;
  61. m_increment_button->set_relative_rect(width() - button_width - frame_thickness, frame_thickness, button_width, button_height);
  62. m_decrement_button->set_relative_rect(width() - button_width - frame_thickness, frame_thickness + button_height, button_width, button_height);
  63. m_editor->set_relative_rect(0, 0, width(), height());
  64. }