043. How to set a button as default action when user press Enter?

Problem

You would like to set a button as default action when user press Enter as shown below:

How to set a button as default action when user press Enter?


Solution


Sample Code

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

// display title
$title = new GtkLabel("Default Button Action");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$title->modify_fg(Gtk::STATE_NORMAL, GdkColor::parse("#0000ff"));
$title->set_size_request(-1, 40);
$vbox->pack_start($title, 0, 0);

$hbox = new GtkHBox();
$vbox->pack_start($hbox, 0, 0);
$hbox->pack_start(new GtkLabel("Keyword: "), 0, 0);
$hbox->pack_start($entry = new GtkEntry(), 0, 0);
$hbox->pack_start($button = new GtkButton("Search"), 0, 0);

$entry->connect('activate', 'on_enter', $button); // note 1
$button->connect('clicked', 'on_click', $entry); // note 2

function on_enter($entry, $button) { // handle Enter key
    $keyword = $entry->get_text(); // get user input
    echo "Enter pressed. keyword = $keyword\n";
    $button->clicked(); // note 3
}

function on_click($button, $entry) { // handle button click
    $keyword = $entry->get_text(); // get user input
    echo "button clicked. keyword = $keyword\n";
}

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

?>

Output

As shown above.

 

Explanation

  1. Set up event handler to listen to Enter key. Note that we pass the ID of the button along. We need the button ID later to simulate button click.
  2. Set up event handler to listen to button click. Note that we pass the ID of the GtkEntry along. We need the GtkEntry ID later to get user input.
  3. We simulate a button click with GtkButton::clicked().

Add comment


Security code
Refresh