GroupBox.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibGUI/GroupBox.h>
  8. #include <LibGUI/Painter.h>
  9. #include <LibGfx/Font/Font.h>
  10. #include <LibGfx/Palette.h>
  11. #include <LibGfx/StylePainter.h>
  12. REGISTER_WIDGET(GUI, GroupBox)
  13. namespace GUI {
  14. GroupBox::GroupBox(StringView title)
  15. : m_title(title)
  16. {
  17. REGISTER_DEPRECATED_STRING_PROPERTY("title", title, set_title);
  18. }
  19. Margins GroupBox::content_margins() const
  20. {
  21. return {
  22. (!m_title.is_empty() ? font().pixel_size_rounded_up() + 1 /*room for the focus rect*/ : 2),
  23. 2,
  24. 2,
  25. 2
  26. };
  27. }
  28. void GroupBox::paint_event(PaintEvent& event)
  29. {
  30. Painter painter(*this);
  31. painter.add_clip_rect(event.rect());
  32. Gfx::IntRect frame_rect {
  33. 0, (!m_title.is_empty() ? font().pixel_size_rounded_up() / 2 : 0),
  34. width(), height() - (!m_title.is_empty() ? font().pixel_size_rounded_up() / 2 : 0)
  35. };
  36. Gfx::StylePainter::paint_frame(painter, frame_rect, palette(), Gfx::FrameStyle::SunkenBox);
  37. if (!m_title.is_empty()) {
  38. // Fill with button background behind the text (covering the frame).
  39. Gfx::IntRect text_background_rect { 6, 1, font().width_rounded_up(m_title) + 6, font().pixel_size_rounded_up() };
  40. painter.fill_rect(text_background_rect, palette().button());
  41. // Center text within button background rect to ensure symmetric padding on both sides.
  42. // Note that we don't use TextAlignment::Center here to avoid subpixel jitter.
  43. Gfx::IntRect text_rect { 0, 0, text_background_rect.width() - 6, text_background_rect.height() };
  44. text_rect.center_within(text_background_rect);
  45. painter.draw_text(text_rect, m_title, Gfx::TextAlignment::CenterLeft, palette().button_text());
  46. }
  47. }
  48. void GroupBox::fonts_change_event(FontsChangeEvent& event)
  49. {
  50. Widget::fonts_change_event(event);
  51. layout_relevant_change_occurred();
  52. }
  53. void GroupBox::set_title(StringView title)
  54. {
  55. if (m_title == title)
  56. return;
  57. m_title = title;
  58. update();
  59. }
  60. }