Horizon
generic_combo_box.hpp
1 #pragma once
2 #include <gtkmm.h>
3 
4 namespace horizon {
5 template <typename T> class GenericComboBox : public Gtk::ComboBox {
6 public:
7  GenericComboBox() : Gtk::ComboBox()
8  {
9  store = Gtk::ListStore::create(list_columns);
10  set_model(store);
11  cr_text = Gtk::manage(new Gtk::CellRendererText);
12  pack_start(*cr_text, true);
13  add_attribute(cr_text->property_text(), list_columns.value);
14 
15  signal_changed().connect([this] {
16  auto it = get_active();
17  if (store->iter_is_valid(it)) {
18  Gtk::TreeModel::Row row = *it;
19  set_tooltip_text(row[list_columns.value]);
20  }
21  else {
22  set_has_tooltip(false);
23  }
24  });
25  }
26 
27  Gtk::CellRendererText &get_cr_text()
28  {
29  return *cr_text;
30  }
31 
32  void set_active_key(const T &key)
33  {
34  for (const auto &it : store->children()) {
35  Gtk::TreeModel::Row row = *it;
36  if (row[list_columns.key] == key) {
37  set_active(it);
38  break;
39  }
40  }
41  }
42 
43  const T get_active_key()
44  {
45  auto it = get_active();
46  if (store->iter_is_valid(it)) {
47  Gtk::TreeModel::Row row = *it;
48  return row[list_columns.key];
49  }
50  else {
51  return T();
52  }
53  }
54 
55  void remove_all()
56  {
57  store->clear();
58  }
59 
60  void append(const T &key, const Glib::ustring &value)
61  {
62  Gtk::TreeModel::Row row = *store->append();
63  row[list_columns.key] = key;
64  row[list_columns.value] = value;
65  }
66 
67 private:
68  class ListColumns : public Gtk::TreeModelColumnRecord {
69  public:
70  ListColumns()
71  {
72  Gtk::TreeModelColumnRecord::add(key);
73  Gtk::TreeModelColumnRecord::add(value);
74  }
75  Gtk::TreeModelColumn<T> key;
76  Gtk::TreeModelColumn<Glib::ustring> value;
77  };
78  ListColumns list_columns;
79 
80  Glib::RefPtr<Gtk::ListStore> store;
81  Gtk::CellRendererText *cr_text = nullptr;
82 };
83 } // namespace horizon
Definition: generic_combo_box.hpp:5