Search code examples
c++stringwidgetinstantiationgtkmm3

How can I dynamically name widget variables in gtkmm3?


I am trying to create 10 Gtk::Buttons without going

Gtk::Button *button1 = new Gtk::Button;
Gtk::Button *button2 = new Gtk::Button;
Gtk::Button *button3 = new Gtk::Button;
...
Gtk::Button *button10 = new Gtk::Button;

grid.add(*button1); grid.add(*button2); grid.add(*button3); //...

A Qt but similar question is here

I have tried the Qt example, but it has filename and I don't know it is for.

For string array (a list with "button1","button2","button3") loop will generate pointer errors here

grid.add(*button1)
         ^_______

What I need to happen is to generate dynamic naming for the Buttons' variables and then perform

grid.add(*button1);
grid.add(*button2);
grid.add(*button3);
...
grid.add(*button4);

Solution

  • Trying to make my question clear I ended up picking information from various people and combined it to the following

    main.cpp

    #include <gtkmm.h>
    #include <map>
    #include <string>
    
    int main(int argc, char *argv[])
    {
      auto app =
        Gtk::Application::create(argc, argv,
          "org.gtkmm.dynamic.buttons");
    
      Gtk::Window window;Gtk::Grid grid;
      window.set_default_size(600, 600);
      std::string name = "button";
      std::map<std::string, Gtk::Button*> all_buttons;
      for (int i = 1; i <= 10; i++)
      {
        Gtk::Button *button = new Gtk::Button("Button " + std::to_string(i));
        all_buttons[name] = button;
        grid.add(*button);
      }
      window.add(grid);
      window.show_all_children();
    
      return app->run(window);
    }
    

    Thanks to ptomato & Peter87