Suppose you would like to ensure that only numbers, i.e. 0 to 9, are allowed to be entered in a GtkEntry field as shown below:
There are many ways to accomplish this. In this example, we will make use of a new function emit_stop_by_name() recently added in by Andrei.
- Use insert-text to let us know everytime the user enters a text.
- If it's a number, let the default handler displays the number.
- If it's not a number, use emit_stop_by_name() to prevent the text from appearing.
To be able to use this function, you need to download the latest copy of php-gtk2 from the cvs repository (gtk.php.net/download.php) and do a recompilation. For linux users, this should take less than 10 minutes to recompile. For windows users using Gnope Installer, we have to wait for the php-gtk2 core team to give us an update of the php-gtk2.dll.
By the way, there are some people telling me that they have problem logging on to the cvs server from countries outside US. If you encounter the same problem, you may drop me a note via the feedback, and I can email you a copy of the php-gtk2 source code on the cvs server.
| 1 |
$window = new GtkWindow();
$window->add($vbox = new GtkVBox());
// display title
$title = new GtkLabel("Allow only numbers in GtkEntry - Part 1");
$title->modify_font(new PangoFontDescription("Times New Roman Italic 10"));
$vbox->pack_start($title, 0, 0);
$vbox->pack_start(new GtkLabel("uses emit_stop_by_name()"), 0, 0);
$item_number = new GtkEntry();
$item_number->connect('insert-text', 'on_insert'); // note 1
$hbox = new GtkHBox();
$hbox->pack_start(new GtkLabel('Item Number: '), 0, 0);
$hbox->pack_start($item_number, 0, 0);
$vbox->pack_start(new GtkLabel("Note: item numbers should contain only numbers 0 to 9"), 0, 0);
- Note that this is only 70% of the sample code. You have to be a registered member to see the entire sample code. Please login or register.
- Registration is free and immediate.
- Have some doubt about the registration? Please read this forum article.
- Notify us when user enters any text.
emit_stop_by_name() to gobble up any text that are not numbers.