0

我需要创建一个只接受数字的 gtk.Entry。但我无法覆盖遗传类中的 key_press_event 事件。它仅在我通过连接功能使用原始条目时才有效。我究竟做错了什么?

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;
}
4

1 回答 1

1

key_press_event不再调用超类的。当您使用密钥时,您需要调用基类并返回 true。

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;
    }
}

如果您在信号中返回 false,则可以将其传递给备用处理程序,但前提是您使用connect而不是覆盖信号方法。

于 2014-08-18T01:57:39.980 回答