Search code examples
c++gtk3gtkmm

Better way to get label from ListBox row?


I'm working with gtkmm (GTK+3), and I'm finding that there are surprisingly few tutorials for working with Gtk::ListBox. I need to be able to extract the label from a single ListBoxRow in ListBox.

Right now, this code works to print the first row's label text to the command line, but it really isn't terribly efficient.

vector<Gtk::Widget*> listChildren = lst_agents.get_children();
vector<Gtk::Widget*> rowChildren = static_cast<Gtk::ListBoxRow*>(listChildren[0])->get_children();
std::cout << static_cast<Gtk::Label*>(rowChildren[0])->get_label() << std::endl;

Is there a better way to do this, ideally without dynamic allocation entering the picture? I cannot imagine that every single Gtk::ListBox sort goes through all of this trouble on each sort, because the CPU overhead would be tremendous!

ENVIRONMENT: Ubuntu 15.04, GNU GCC, Code::Blocks, C+11


Solution

  • I don't think there's a better way, no. I see no great problem with it other than that you have to get a list of all child widgets just to get the first one.

    A ListBox sort would involve implementing a set_sort_func() callback slot: https://developer.gnome.org/gtkmm/stable/classGtk_1_1ListBox.html#acec1d5f8d73d591fc3eb2772c4f0e480

    and then you would already have the ListBoxRow: https://developer.gnome.org/gtkmm/stable/classGtk_1_1ListBox.html#a931a0b125d6514e0191a071900bf57c0

    so there wouldn't be much work to do. Anyway, ListBox isn't meant for showing huge numbers of items - for that you would want a container widget that reused the child widgets to present a data model - for instance, Gtk::TreeView.

    You also have a typo in the second line of your code: You couldn't cast a ListBoxRow to a vector.