GListBox.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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& event)
  17. {
  18. Painter painter(*this);
  19. painter.set_clip_rect(event.rect());
  20. painter.fill_rect({ rect().x() + 1, rect().y() + 1, rect().width() - 2, rect().height() - 2 }, background_color());
  21. painter.draw_rect(rect(), foreground_color());
  22. if (is_focused())
  23. painter.draw_focus_rect(rect());
  24. for (int i = m_scroll_offset; i < static_cast<int>(m_items.size()); ++i) {
  25. auto item_rect = this->item_rect(i);
  26. Rect text_rect(item_rect.x() + 1, item_rect.y() + 1, item_rect.width() - 2, item_rect.height() - 2);
  27. Color item_text_color = foreground_color();
  28. if (m_selected_index == i) {
  29. if (is_focused())
  30. painter.fill_rect(item_rect, Color(0, 32, 128));
  31. else
  32. painter.fill_rect(item_rect, Color(96, 96, 96));
  33. item_text_color = Color::White;
  34. }
  35. painter.draw_text(item_rect, m_items[i], TextAlignment::TopLeft, item_text_color);
  36. }
  37. }
  38. void GListBox::mousedown_event(GMouseEvent& event)
  39. {
  40. dbgprintf("GListBox::mouseDownEvent %d,%d\n", event.x(), event.y());
  41. for (int i = m_scroll_offset; i < static_cast<int>(m_items.size()); ++i) {
  42. auto item_rect = this->item_rect(i);
  43. if (item_rect.contains(event.position())) {
  44. m_selected_index = i;
  45. dbgprintf("GListBox: selected item %u (\"%s\")\n", i, m_items[i].characters());
  46. update();
  47. return;
  48. }
  49. }
  50. }
  51. void GListBox::add_item(String&& item)
  52. {
  53. m_items.append(move(item));
  54. if (m_selected_index == -1)
  55. m_selected_index = 0;
  56. }