GLabel.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "GLabel.h"
  2. #include <LibGUI/GPainter.h>
  3. #include <LibDraw/GraphicsBitmap.h>
  4. GLabel::GLabel(GWidget* parent)
  5. : GFrame(parent)
  6. {
  7. }
  8. GLabel::GLabel(const StringView& text, GWidget* parent)
  9. : GFrame(parent)
  10. , m_text(text)
  11. {
  12. }
  13. GLabel::~GLabel()
  14. {
  15. }
  16. void GLabel::set_icon(GraphicsBitmap* icon)
  17. {
  18. m_icon = icon;
  19. }
  20. void GLabel::set_text(const StringView& text)
  21. {
  22. if (text == m_text)
  23. return;
  24. m_text = move(text);
  25. update();
  26. }
  27. void GLabel::paint_event(GPaintEvent& event)
  28. {
  29. GFrame::paint_event(event);
  30. GPainter painter(*this);
  31. painter.add_clip_rect(event.rect());
  32. if (m_icon) {
  33. if (m_should_stretch_icon) {
  34. painter.draw_scaled_bitmap(frame_inner_rect(), *m_icon, m_icon->rect());
  35. } else {
  36. auto icon_location = frame_inner_rect().center().translated(-(m_icon->width() / 2), -(m_icon->height() / 2));
  37. painter.blit(icon_location, *m_icon, m_icon->rect());
  38. }
  39. }
  40. if (text().is_empty())
  41. return;
  42. int indent = 0;
  43. if (frame_thickness() > 0)
  44. indent = font().glyph_width('x') / 2;
  45. auto text_rect = frame_inner_rect();
  46. text_rect.move_by(indent, 0);
  47. text_rect.set_width(text_rect.width() - indent * 2);
  48. if (is_enabled()) {
  49. painter.draw_text(text_rect, text(), m_text_alignment, foreground_color(), TextElision::Right);
  50. } else {
  51. painter.draw_text(text_rect.translated(1, 1), text(), font(), text_alignment(), Color::White, TextElision::Right);
  52. painter.draw_text(text_rect, text(), font(), text_alignment(), Color::from_rgb(0x808080), TextElision::Right);
  53. }
  54. }
  55. void GLabel::size_to_fit()
  56. {
  57. set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
  58. set_preferred_size({ font().width(m_text), 0 });
  59. }