Search code examples
gtkmm

How can I count the widgets stored in a Gtk::Grid?


I am looking for several gtkmm methods/data types that are equivalent to some QT expressions:

  1. given a widget container in QT (e.g. QBoxLayout), a simple method called count() returns the amout of widgets stored in the given container. The best way to exchange QBoxLayout or any QT widget container is Gtk::Grid. But there is no simple way to get the amount of widgets inside of it. Same with Gtk::Box.

    I need that method to iterate the childs stored in the grid:

    for(auto& it : layouts) { //layouts is a vector of Gtk::Grids         
        for(int i = 0; i < it->size(); ++i) {                                                                
            if(it->get_child_at(0, i)) {  
                it->get_child_at(0, i)->set_visible((std::string(it->get_name())== StringID));                       
            }
    
  2. QT uses QWidget as an object unbounded to any widget type (such as a button or a checkbox..). That is not possible in gtkmm, because Widgets can only be initinalized with a reference to a widget type. Now I'm looking to replace a QT code with gtkmm, that has a vector of widgets. I used Gtk::Box to replace the QWidgets. Is that a reasonable replacement? I'm getting trouble replacing their scale, which was originally dealt with using QSize, expecting two numbers "hight" and "lenght". Now there is a Gtk::Scale class, but it works in a different way..


Solution

  • All Gtkmm containers (like Gtk::Grid) inherit from the Gtk::Container, which makes the following methods available:

    std::vector<Widget*> get_children()               // Non const: to modify the widgets
    std::vector<const Widget*> get_children () const  // const: for read operations
    

    These methods return exactly what you want: a vector of widgets. You can use size() on the returned std::vector to count the number of wigets in the container.

    Also, in my opinion, Gtk::Box is very rarely useful since it is very limited. Gtk::Grid is almost always a better choice.

    Finally, in Qt, all graphical elements inherit from QWidget. In Gtkmm, all widgets inherit from Gtk::Widget, meaning that you can write something like:

    Gtk::Widget* pButton = new Gtk::Button("My button");
    

    and then use pButton, which is "unbounded to any widget type". See the reference for more information on Gtk::Widget.


    Update for Gtkmm4

    It seems Gtk::Container was removed in Gtkmm4 as documented here. There seems to be nothing to replace it. Unfortunately, it looks like in this version, child widgets tracking will have to be done manually.