The problem of setting the current page of a GtkNotebook not working in GTK2

⌚Time: 2026-07-14 16:59:00

👨‍💻Author: Jack Ge

My original code was like this

GtkWidget *lab1  = gtk_label_new("111111111111111111");
gtk_notebook_insert_page(GTK_NOTEBOOK(g_notebook), lab1, NULL,0);
    
GtkWidget *lab2  = gtk_label_new("2222222222222222222222");
gtk_notebook_insert_page(GTK_NOTEBOOK(g_notebook), lab2, NULL,1);
    
GtkWidget *lab3  = gtk_label_new("33333333333333");
gtk_notebook_insert_page(GTK_NOTEBOOK(g_notebook), lab3, NULL,2);

//Set page 1 as the default page
gtk_notebook_set_current_page(GTK_NOTEBOOK(g_notebook), 1);

...

gtk_widget_show_all(g_notebook);

No matter which page I set as the current page, it always shows page 0 with "111111111111111". I get the current page number after setting it.

gtk_notebook_set_current_page(GTK_NOTEBOOK(g_notebook), 1);
g_print("after settinh, current page index: %d\n", gtk_notebook_get_current_page(GTK_NOTEBOOK(g_notebook)));

...

gtk_widget_show_all(g_notebook);

It will print -1, return -1 means the GtkNoteBook is an empty page.

after settinh, current page index: -1

The problem is with the gtk_widget_show_all function. When gtk_widget_show_all runs, it recursively shows all child widgets and triggers each widget's signals, which can override previous settings and cause them to fail. So you just need to put the setup code after gtk_widget_show_all.


gtk_widget_show_all(g_notebook);

...

gtk_notebook_set_current_page(GTK_NOTEBOOK(g_notebook), 1);
g_print("after settinh, current page index: %d\n", gtk_notebook_get_current_page(GTK_NOTEBOOK(g_notebook)));

At this point, you'll notice that the default page has changed to page 1. The printout shows:

after setting, current page index: 1

GtkNotebook will by default show page 0. You can also skip setting the current page through code and just set the default displayed page number to 0.

Previously, gtk_notebook_get_current_page returned -1 to mean that there was no page. A possible reason is that when setting the current page, the page hadn't been created and displayed yet. So any settings wouldn't work. It's only after executing gtk_widget_show_all that the widget will be actually displayed.

In GTK2, triggering widget signals often doesn’t work until the widget has been properly drawn and updated. This happens with other widgets too. Take GtkEntry, for example. If you set some text in code and then immediately try to get it, you won’t get anything because the GtkEntry interface hasn’t been updated yet. For situations like this, using a function like g_idle_add to run the needed actions when the main loop is idle will solve the problem.