eventsgtkvalagtkentry

Vala GTK+. Issue with customized widget


I need to create a gtk.Entry which accepts only numbers. but I can't overwrite the key_press_event event in an heredited class. It only works if I use the original Entry by means of connect function. What am I doing wrong?

using Gtk;

public class NumberEntry : Entry {

    public void NumberEntry(){
        add_events (Gdk.EventMask.KEY_PRESS_MASK);
    }
    //With customized event left entry editing is not possible
    public override bool key_press_event (Gdk.EventKey event) {
        string numbers = "0123456789.";
            if (numbers.contains(event.str)){
               return false;
            } else {
               return true;
            }
        }
    }

public class Application : Window {

    public Application () {
        // Window
        this.title = "Entry Issue";
        this.window_position = Gtk.WindowPosition.CENTER;
        this.destroy.connect (Gtk.main_quit);
        this.set_default_size (350, 70);

        Grid grid = new Grid();
        grid.set_row_spacing(8);
        grid.set_column_spacing(8);

        Label label_1 = new Label ("Customized Entry, useless:");
        grid.attach (label_1,0,0,1,1);

        //Customized Entry:
        NumberEntry numberEntry = new NumberEntry ();
        grid.attach(numberEntry, 1, 0, 1, 1);

        Label label_2 = new Label ("Working only numbers Entry:");
        grid.attach (label_2,0,1,1,1);

        //Normal Entry
        Entry entry = new Entry();
        grid.attach(entry, 1, 1, 1, 1);


        this.add(grid);

        //With normal Entry this event works well:
        entry.key_press_event.connect ((event) => {
            string numbers = "0123456789.";
            if (numbers.contains(event.str)){
                return false;
            } else {
                return true;
            }
        });
    }
}

public static int main (string[] args) {
    Gtk.init (ref args);

    Application app = new Application ();
    app.show_all ();
    Gtk.main ();
    return 0;
}

Solution

  • The key_press_event of the superclass is no longer being called. You need to call the base class and return true when you have consumed the key.

    public override bool key_press_event (Gdk.EventKey event) {
        string numbers = "0123456789.";
        if (numbers.contains(event.str)){
           return base.key_press_event (event);
        } else {
           return true;
        }
    }
    

    If you return false in a signal, this can be passed to an alternate handler, but only if you use connect and not override the signal method.