Button.cpp 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #include "Button.h"
  2. #include "Painter.h"
  3. Button::Button(Widget* parent)
  4. : Widget(parent)
  5. {
  6. setFillWithBackgroundColor(false);
  7. }
  8. Button::~Button()
  9. {
  10. }
  11. void Button::setCaption(String&& caption)
  12. {
  13. if (caption == m_caption)
  14. return;
  15. m_caption = move(caption);
  16. update();
  17. }
  18. void Button::paintEvent(PaintEvent&)
  19. {
  20. Color buttonColor = Color::LightGray;
  21. Color highlightColor = Color::White;
  22. Color shadowColor = Color(96, 96, 96);
  23. Painter painter(*this);
  24. painter.draw_line({ 1, 0 }, { width() - 2, 0 }, Color::Black);
  25. painter.draw_line({ 1, height() - 1 }, { width() - 2, height() - 1}, Color::Black);
  26. painter.draw_line({ 0, 1 }, { 0, height() - 2 }, Color::Black);
  27. painter.draw_line({ width() - 1, 1 }, { width() - 1, height() - 2 }, Color::Black);
  28. if (m_beingPressed) {
  29. // Base
  30. painter.fill_rect({ 1, 1, width() - 2, height() - 2 }, buttonColor);
  31. // Sunken shadow
  32. painter.draw_line({ 1, 1 }, { width() - 2, 1 }, shadowColor);
  33. painter.draw_line({ 1, 2 }, {1, height() - 2 }, shadowColor);
  34. } else {
  35. // Base
  36. painter.fill_rect({ 3, 3, width() - 5, height() - 5 }, buttonColor);
  37. // White highlight
  38. painter.draw_line({ 1, 1 }, { width() - 2, 1 }, highlightColor);
  39. painter.draw_line({ 1, 2 }, { width() - 3, 2 }, highlightColor);
  40. painter.draw_line({ 1, 3 }, { 1, height() - 2 }, highlightColor);
  41. painter.draw_line({ 2, 3 }, { 2, height() - 3 }, highlightColor);
  42. // Gray shadow
  43. painter.draw_line({ width() - 2, 1 }, { width() - 2, height() - 4 }, shadowColor);
  44. painter.draw_line({ width() - 3, 2 }, { width() - 3, height() - 4 }, shadowColor);
  45. painter.draw_line({ 1, height() - 2 }, { width() - 2, height() - 2 }, shadowColor);
  46. painter.draw_line({ 2, height() - 3 }, { width() - 2, height() - 3 }, shadowColor);
  47. }
  48. if (!caption().is_empty()) {
  49. auto textRect = rect();
  50. if (m_beingPressed)
  51. textRect.move_by(1, 1);
  52. painter.draw_text(textRect, caption(), Painter::TextAlignment::Center, Color::Black);
  53. }
  54. }
  55. void Button::mouseDownEvent(MouseEvent& event)
  56. {
  57. printf("Button::mouseDownEvent: x=%d, y=%d, button=%u\n", event.x(), event.y(), (unsigned)event.button());
  58. m_beingPressed = true;
  59. update();
  60. Widget::mouseDownEvent(event);
  61. }
  62. void Button::mouseUpEvent(MouseEvent& event)
  63. {
  64. printf("Button::mouseUpEvent: x=%d, y=%d, button=%u\n", event.x(), event.y(), (unsigned)event.button());
  65. m_beingPressed = false;
  66. update();
  67. Widget::mouseUpEvent(event);
  68. if (onClick)
  69. onClick(*this);
  70. }