【问题标题】:Vala GTK+. Issue with customized widget瓦拉 GTK+。自定义小部件的问题
【发布时间】:2017-09-01 10:05:25
【问题描述】:

我需要创建一个只接受数字的 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;
}

【问题讨论】:

    标签: events gtk vala gtkentry


    【解决方案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 并且不覆盖信号方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多