Hello.
How do you determine the page that should be closed? Getting page by number will break as soon as one non-last page is removed from notebook and deleting current page will fail if user tries to close non-active page.
The way I usually do this is to store the actual widget that holds content of the notebook page into close button itself. This serves as a unique identifier to the notebook page (since widget cannot be added to two pages at the same time) and removing that page is then really painless and safe.
Sample code is attached below.
Cheers,
Tadej
Code:
#include <gtk/gtk.h>
static const char *images[] = { GTK_STOCK_FLOPPY,
GTK_STOCK_HARDDISK,
GTK_STOCK_PRINT,
GTK_STOCK_CUT };
static void
cb_close_tab (GtkButton *button,
GtkNotebook *notebook)
{
GtkWidget *page;
int page_no;
page = GTK_WIDGET (g_object_get_data (G_OBJECT (button), "page"));
page_no = gtk_notebook_page_num (notebook, page);
gtk_notebook_remove_page (notebook, page_no);
}
static void
append_notebook_page (GtkNotebook *notebook,
char const *name)
{
GtkWidget *image, *hbox, *close, *label, *icon;
/* Main contents */
image = gtk_image_new_from_stock (name, GTK_ICON_SIZE_DIALOG);
gtk_widget_show (image);
/* Tab contents */
hbox = gtk_hbox_new (FALSE, 5);
label = gtk_label_new (name);
gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
close = gtk_button_new ();
g_object_set_data (G_OBJECT (close), "page", image);
g_signal_connect (close, "clicked", G_CALLBACK (cb_close_tab), notebook);
gtk_box_pack_start (GTK_BOX (hbox), close, FALSE, FALSE, 0);
icon = gtk_image_new_from_stock (GTK_STOCK_CLOSE, GTK_ICON_SIZE_MENU);
gtk_container_add (GTK_CONTAINER (close), icon);
gtk_widget_show_all (hbox);
/* Add page to the end */
gtk_notebook_append_page (notebook, image, hbox);
}
int
main (int argc,
char **argv)
{
GtkWidget *window,
*notebook;
size_t i, size;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
g_signal_connect (window, "destroy", gtk_main_quit, NULL);
notebook = gtk_notebook_new ();
gtk_container_add (GTK_CONTAINER (window), notebook);
/* Create several pages */
size = G_N_ELEMENTS (images);
for (i = 0; i < size; i++)
{
append_notebook_page (GTK_NOTEBOOK (notebook),
images[i]);
}
gtk_widget_show_all (window);
gtk_main ();
return 0;
}