CheckBox.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGUI/CheckBox.h>
  7. #include <LibGUI/Painter.h>
  8. #include <LibGfx/CharacterBitmap.h>
  9. #include <LibGfx/Font.h>
  10. #include <LibGfx/Palette.h>
  11. #include <LibGfx/StylePainter.h>
  12. REGISTER_WIDGET(GUI, CheckBox)
  13. namespace GUI {
  14. static const int s_box_width = 13;
  15. static const int s_box_height = 13;
  16. static const int s_horizontal_padding = 6;
  17. CheckBox::CheckBox(String text)
  18. : AbstractButton(move(text))
  19. {
  20. REGISTER_BOOL_PROPERTY("autosize", is_autosize, set_autosize);
  21. set_min_width(32);
  22. set_fixed_height(22);
  23. }
  24. CheckBox::~CheckBox()
  25. {
  26. }
  27. void CheckBox::paint_event(PaintEvent& event)
  28. {
  29. Painter painter(*this);
  30. painter.add_clip_rect(event.rect());
  31. auto text_rect = rect();
  32. text_rect.set_left(s_box_width + s_horizontal_padding);
  33. text_rect.set_width(font().width(text()));
  34. text_rect.set_top(height() / 2 - font().glyph_height() / 2);
  35. text_rect.set_height(font().glyph_height());
  36. if (fill_with_background_color())
  37. painter.fill_rect(rect(), palette().window());
  38. if (is_enabled() && is_hovered())
  39. painter.fill_rect(rect(), palette().hover_highlight());
  40. Gfx::IntRect box_rect {
  41. 0, height() / 2 - s_box_height / 2 - 1,
  42. s_box_width, s_box_height
  43. };
  44. Gfx::StylePainter::paint_check_box(painter, box_rect, palette(), is_enabled(), is_checked(), is_being_pressed());
  45. paint_text(painter, text_rect, font(), Gfx::TextAlignment::TopLeft);
  46. if (is_focused())
  47. painter.draw_focus_rect(text_rect.inflated(6, 6), palette().focus_outline());
  48. }
  49. void CheckBox::click(unsigned)
  50. {
  51. if (!is_enabled())
  52. return;
  53. set_checked(!is_checked());
  54. }
  55. void CheckBox::set_autosize(bool autosize)
  56. {
  57. if (m_autosize == autosize)
  58. return;
  59. m_autosize = autosize;
  60. if (m_autosize)
  61. size_to_fit();
  62. }
  63. void CheckBox::size_to_fit()
  64. {
  65. set_fixed_width(s_box_width + font().width(text()) + s_horizontal_padding * 2);
  66. }
  67. }