Search code examples
gtkgtk3valagnome-builder

Adding an element after clicking on a button


I was trying to learn Vala by programming a very simple application and I stumbled over a problem, that I was unable to resolve on my own.

The program shows simply a button Init and on click it should add a Button X to the Grid container. Unfortunately, the contents of the Grid container remain empty and I don't know why.

Even more confusing is, that adding the Button right in the constructor works as expected.

So what I'm doing wrong here?

using Gtk;

class MyWindow: Gtk.Window {
    private Gtk.Grid mGrid;

    public MyWindow() {
        var init=new Gtk.Button.with_label("Init");
        init.clicked.connect((t)=>{
            stdout.printf("Init");
            mGrid.attach(new Gtk.Button.with_label("X"),0,0,1,1);
        });
        var box=new Gtk.Box(VERTICAL,0);
        mGrid=new Gtk.Grid();
        //mGrid.attach(new Gtk.Button.with_label("X"),0,0,1,1);
        box.add(init);
        box.add(mGrid);
        this.add(box);
        this.show_all();
    }
}

int main(string[] args) {
    Gtk.init(ref args);
    new MyWindow();
    Gtk.main();
    return 0;
}

Solution

  • With the GTK+ toolkit widgets are hidden by default. Although you have this.show_all (), the button is created afterwards and is hidden. Changing the callback from:

    init.clicked.connect((t)=>{
      stdout.printf("Init");
      mGrid.attach(new Gtk.Button.with_label("X"),0,0,1,1);
    });
    

    to something like:

    init.clicked.connect((t)=>{
      stdout.printf("Init");
      var my_button = new Gtk.Button.with_label("X");
      my_button.show_all ();
      mGrid.attach(my_button,0,0,1,1);
    });
    

    now works.