GListBox.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "GListBox.h"
  2. #include <SharedGraphics/Font.h>
  3. #include <SharedGraphics/Painter.h>
  4. GListBox::GListBox(GWidget* parent)
  5. : GWidget(parent)
  6. {
  7. }
  8. GListBox::~GListBox()
  9. {
  10. }
  11. Rect GListBox::item_rect(int index) const
  12. {
  13. int item_height = font().glyph_height() + 2;
  14. return Rect { 2, 2 + (index * item_height), width() - 4, item_height };
  15. }
  16. void GListBox::paint_event(GPaintEvent&)
  17. {
  18. Painter painter(*this);
  19. painter.fill_rect({ rect().x() + 1, rect().y() + 1, rect().width() - 2, rect().height() - 2 }, background_color());
  20. painter.draw_rect(rect(), foreground_color());
  21. if (is_focused())
  22. painter.draw_focus_rect(rect());
  23. for (int i = m_scroll_offset; i < static_cast<int>(m_items.size()); ++i) {
  24. auto item_rect = this->item_rect(i);
  25. Rect text_rect(item_rect.x() + 1, item_rect.y() + 1, item_rect.width() - 2, item_rect.height() - 2);
  26. Color item_text_color = foreground_color();
  27. if (m_selected_index == i) {
  28. if (is_focused())
  29. painter.fill_rect(item_rect, Color(0, 32, 128));
  30. else
  31. painter.fill_rect(item_rect, Color(96, 96, 96));
  32. item_text_color = Color::White;
  33. }
  34. painter.draw_text(item_rect, m_items[i], TextAlignment::TopLeft, item_text_color);
  35. }
  36. }
  37. void GListBox::mousedown_event(GMouseEvent& event)
  38. {
  39. dbgprintf("GListBox::mouseDownEvent %d,%d\n", event.x(), event.y());
  40. for (int i = m_scroll_offset; i < static_cast<int>(m_items.size()); ++i) {
  41. auto item_rect = this->item_rect(i);
  42. if (item_rect.contains(event.position())) {
  43. m_selected_index = i;
  44. dbgprintf("GListBox: selected item %u (\"%s\")\n", i, m_items[i].characters());
  45. update();
  46. return;
  47. }
  48. }
  49. }
  50. void GListBox::add_item(String&& item)
  51. {
  52. m_items.append(move(item));
  53. if (m_selected_index == -1)
  54. m_selected_index = 0;
  55. }