GRadioButton.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <LibDraw/GraphicsBitmap.h>
  2. #include <LibGUI/GPainter.h>
  3. #include <LibGUI/GRadioButton.h>
  4. static RefPtr<GraphicsBitmap> s_unfilled_circle_bitmap;
  5. static RefPtr<GraphicsBitmap> s_filled_circle_bitmap;
  6. static RefPtr<GraphicsBitmap> s_changing_filled_circle_bitmap;
  7. static RefPtr<GraphicsBitmap> s_changing_unfilled_circle_bitmap;
  8. GRadioButton::GRadioButton(GWidget* parent)
  9. : GRadioButton({}, parent)
  10. {
  11. }
  12. GRadioButton::GRadioButton(const StringView& text, GWidget* parent)
  13. : GAbstractButton(text, parent)
  14. {
  15. if (!s_unfilled_circle_bitmap) {
  16. s_unfilled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/unfilled-radio-circle.png");
  17. s_filled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/filled-radio-circle.png");
  18. s_changing_filled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/changing-filled-radio-circle.png");
  19. s_changing_unfilled_circle_bitmap = GraphicsBitmap::load_from_file("/res/icons/changing-unfilled-radio-circle.png");
  20. }
  21. }
  22. GRadioButton::~GRadioButton()
  23. {
  24. }
  25. Size GRadioButton::circle_size()
  26. {
  27. return s_unfilled_circle_bitmap->size();
  28. }
  29. static const GraphicsBitmap& circle_bitmap(bool checked, bool changing)
  30. {
  31. if (changing)
  32. return checked ? *s_changing_filled_circle_bitmap : *s_changing_unfilled_circle_bitmap;
  33. return checked ? *s_filled_circle_bitmap : *s_unfilled_circle_bitmap;
  34. }
  35. void GRadioButton::paint_event(GPaintEvent& event)
  36. {
  37. GPainter painter(*this);
  38. painter.add_clip_rect(event.rect());
  39. Rect circle_rect { { 2, 0 }, circle_size() };
  40. circle_rect.center_vertically_within(rect());
  41. auto& bitmap = circle_bitmap(is_checked(), is_being_pressed());
  42. painter.blit(circle_rect.location(), bitmap, bitmap.rect());
  43. Rect text_rect { circle_rect.right() + 4, 0, font().width(text()), font().glyph_height() };
  44. text_rect.center_vertically_within(rect());
  45. paint_text(painter, text_rect, font(), TextAlignment::TopLeft);
  46. }
  47. template<typename Callback>
  48. void GRadioButton::for_each_in_group(Callback callback)
  49. {
  50. if (!parent())
  51. return;
  52. parent()->for_each_child_of_type<GRadioButton>([&](auto& child) {
  53. return callback(static_cast<GRadioButton&>(child));
  54. });
  55. }
  56. void GRadioButton::click()
  57. {
  58. if (!is_enabled())
  59. return;
  60. for_each_in_group([this](auto& button) {
  61. if (&button != this)
  62. button.set_checked(false);
  63. return IterationDecision::Continue;
  64. });
  65. set_checked(true);
  66. }