090. How to know which tab of GtkNotebook is being clicked on?

Problem

You want to know which tab of GtkNotebook is being clicked on as shown below:

How to know which tab of GtkNotebook is being clicked on?


Solution


Sample Code

1   
2   
3   
4   
5   
6   
7   
8   
10   
11   
12   
13   
14   
15   
16   
17   
18   
19   
21   
23   
24   
25   
26   
27   
28   
29   
30   
31   
32   
33   
34   
35   
36   
37   
38   
39   
40   
41   
42   
43   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 240);
$window->connect_simple('destroy', array('Gtk','main_quit'));
$window->add($vbox = new GtkVBox());

// setup notebook
$notebook = new GtkNotebook(); // note 1
$vbox->pack_start($notebook);

// add two tabs of GtkLabel
add_new_tab($notebook, new GtkLabel('Notebook 1'), 'Label #1');
add_new_tab($notebook, new GtkLabel('Notebook 2'), 'Label #2');

// add a thrid tab of GtkTextView
$buffer = new GtkTextBuffer();
$view = new GtkTextView();
$view->set_buffer($buffer);
$view->set_wrap_mode(Gtk::WRAP_WORD);
add_new_tab($notebook, $view, 'TextView');

$window->show_all();
Gtk::main();

// add new tab
function add_new_tab($notebook, $widget, $tab_label) {
    $eventbox = new GtkEventBox();
    $label = new GtkLabel($tab_label);
    $eventbox->add($label); // note 2
    $label->show(); // note 3
    $eventbox->connect('button-press-event', 'on_tab', $tab_label); // note 4
    $notebook->append_page($widget, $eventbox); // note 5
}

// function that is called when user click on tab
function on_tab($widget, $event, $tab_label) {  // note 6
    echo "tab clicked = $tab_label\n";
}

?>

Output

As shown above.
 

Explanation

What's new here:

  1. Set up a new notebook.
  2. Create a GtkEventBox and stuff the tab label inside.
  3. Don't forget this!!! Othewise the tab label would not show!
  4. Set up event handler to listen to button click on tab. Note that we passed the $tab_label along so that we know later which tab is being clicked on.
  5. Append a new page to the notebook with $widget as the content and the $eventbox as the tab label. In this example, we set up the first two tabs as GtkLabel, and the third as GtkTextView.
  6. This is the function that is called when the user clicks on a tab. The variable $tab_label allow us to know which tab the user clicked on.

Related Links

Add comment


Security code
Refresh