GLabel.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. if (m_icon == icon)
  19. return;
  20. m_icon = icon;
  21. update();
  22. }
  23. void GLabel::set_text(const StringView& text)
  24. {
  25. if (text == m_text)
  26. return;
  27. m_text = text;
  28. update();
  29. }
  30. void GLabel::paint_event(GPaintEvent& event)
  31. {
  32. GFrame::paint_event(event);
  33. GPainter painter(*this);
  34. painter.add_clip_rect(event.rect());
  35. if (m_icon) {
  36. if (m_should_stretch_icon) {
  37. painter.draw_scaled_bitmap(frame_inner_rect(), *m_icon, m_icon->rect());
  38. } else {
  39. auto icon_location = frame_inner_rect().center().translated(-(m_icon->width() / 2), -(m_icon->height() / 2));
  40. painter.blit(icon_location, *m_icon, m_icon->rect());
  41. }
  42. }
  43. if (text().is_empty())
  44. return;
  45. int indent = 0;
  46. if (frame_thickness() > 0)
  47. indent = font().glyph_width('x') / 2;
  48. auto text_rect = frame_inner_rect();
  49. text_rect.move_by(indent, 0);
  50. text_rect.set_width(text_rect.width() - indent * 2);
  51. if (is_enabled()) {
  52. painter.draw_text(text_rect, text(), m_text_alignment, foreground_color(), TextElision::Right);
  53. } else {
  54. painter.draw_text(text_rect.translated(1, 1), text(), font(), text_alignment(), Color::White, TextElision::Right);
  55. painter.draw_text(text_rect, text(), font(), text_alignment(), Color::from_rgb(0x808080), TextElision::Right);
  56. }
  57. }
  58. void GLabel::size_to_fit()
  59. {
  60. set_size_policy(SizePolicy::Fixed, SizePolicy::Fill);
  61. set_preferred_size(font().width(m_text), 0);
  62. }