Re: trapping entry key-presses




johannes@nada.kth.se (Johannes Keukelaar) writes:

> //
> //Is there any way to not allow some Key-Press events through to an
> //Entry widget?  I'd like to use an entry, but I need to filter what
> //characters are allowed in the Entry box.  Also, is it possible to
> //right justify the contents of an entry?
> 
> As for filtering the characters, here's what you do: You connect to the key 
> press signal and end up in the queue of handlers _before_ the entry box' 
> handler. (Since the key_press_event signal is created in gtkwidget.c with 
> GTK_RUN_LAST, you don't have to do anything special for that. Just 
> gtk_signal_connect.) Then, if it's a key you don't like, stop the emission of 
> the signal (gtk_signal_emit_stop_by_name). And hey, presto, the entry box will 
> never see it. (Right, wizards?)

This works fine, but people will still be able to paste invalid
characters into your entry. A more reliable way to filter an
Entry is to connect to "insert_text".

The callback to "insert_text" has four parameters:

 GtkEditabele *editable
 const gchar *new_text
 gint  new_text_length
 gint *position

So, the simplest thing to do, is to connect to "insert_text",
and if 'new_text' includes any unwanted characters, call

 gtk_signal_emit_stop_by_name() 

which will prevent the default handler from being run, and thus
prevent any text from being inserted.

(If you were getting fancy, you could make a copy, strip out the
unwanted characters and leave only the valid ones, block yourself,
then call gtk_editable_insert_text() with the new string, but I'm not
sure the result would be more user-friendly in the end)

Regards,
                                        Owen



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]