Search code examples
c++gtkgtk3gtkmmgtkmm3

"Name: value" widget via GTK


How to make a widget via GTK that looks like the following?

------------------
| Text1:    | 1  |
|-----------+----|
| Text2:    | 10 |
|-----------+----|
|           |    |
|           |    |
|           |    |
------------------

'Text1', 'Text2' - constant strings; '1', '10' - dynamically changed values.

What Gtk::Widget's should I use for that?


Solution

  • Make Gtk::Grid with labels, align them, set column spacing and column homogeneous.

    #include <gtkmm.h>
    
    class window : public Gtk::Window {
    protected:
        Gtk::Box box;
        Gtk::Grid grid;
        Gtk::Button button;
        Gtk::Label name1, name2, value1, value2;
        int n_click = 0;
    
    public:
        window();
        ~window() = default;
    
        void on_click() {
            value1.set_label("1");
            value2.set_label(n_click % 2 ? "1" : "10");
            n_click++;
            queue_draw();
        }
    };
    
    window::window() : button("Update"),
            name1("Text:"),
            name2("Text2:")
    {
        add(box);
    
        box.pack_start(button);
        button.signal_clicked().connect(sigc::mem_fun(*this, &window::on_click));
    
        box.pack_end(grid, Gtk::PACK_SHRINK);
        grid.attach(name1,  0, 0, 2, 1);
        grid.attach(value1, 2, 0, 1, 1);
        grid.attach(name2,  0, 1, 2, 1);
        grid.attach(value2, 2, 1, 1, 1);
    
        name1.set_halign(Gtk::ALIGN_START);
        name2.set_halign(Gtk::ALIGN_START);
        value1.set_halign(Gtk::ALIGN_START);
        value2.set_halign(Gtk::ALIGN_START);
        grid.set_column_spacing(10);
        grid.set_column_homogeneous(true);
    
        show_all();
    }
    
    int main(int argc, char *argv[])
    {
        auto app = Gtk::Application::create(argc, argv, "");
    
        window win;
        return app->run(win);
    }