GRadioButton.cpp 2.4 KB

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