eexpress
eexpress

Reputation: 456

How to get key press work in St.Entry of gjs

I want to press the 'Enter' key to call a function; I test many codes in key-press-event part, but no one work. I also don't know which key_symbol is the right one between those Clutter.KEY_Escape KEY_ISO_Enter KEY_KP_Enter KEY_3270_Enter.

other signal like 'primary-icon-clicked' works.

https://gjs-docs.gnome.org/clutter9~9_api/clutter.actor#signal-key-press-event almost say nothing.

        let input = new St.Entry({
            name: 'searchEntry',
            style_class: 'big_text',
            primary_icon: new St.Icon({ gicon: local_icon("countdown-symbolic.svg") }),
            secondary_icon: new St.Icon({ gicon: local_icon("stopwatch-symbolic.svg") }),
            can_focus: true,
            hint_text: _('xxxx'),
            track_hover: true,
            x_expand: true,
        });
        input.connect('primary-icon-clicked', ()=>{add_timer();});
        input.connect('secondary-icon-clicked', ()=>{add_timer();});
        //~ input.connect('key-press-event', (event)=>{if(event.get_key_symbol() == Clutter.KEY_Left)add_timer();});
        input.connect('key-press-event', (self, event)=>{
            //~ let [success, keyval] = event.get_keyval();
            //~ let keyname = Gdk.keyval_name(keyval);
            //~ if (keyname === "Control_L"){add_timer();}
            //~ const symbol = event.get_key_symbol();
            //~ if (symbol === Clutter.KEY_KP_Enter) {add_timer(); return true;}
            //~ if (event.get_key_symbol() === Clutter.KEY_Enter){add_timer();}
            //~ if(event.keyval == Clutter.KEY_Enter){add_timer();} Clutter.KEY_Escape KEY_ISO_Enter KEY_KP_Enter KEY_3270_Enter KEY_equal
            });
        item_input.add(input);

Upvotes: 1

Views: 499

Answers (1)

andy.holmes
andy.holmes

Reputation: 3696

If you want to run a callback when Enter is pressed in the entry, you probably want to connect to the activate signal of the child Clutter.Text actor:

let entry = new St.Entry();

entry.clutter_text.connect('activate', (actor) => {
    log(`Activated: ${actor.text}`);
});

For filtering input, note that Clutter.InputContentPurpose and Clutter.InputContentHintFlags are just hints for the input method. In other words, this is like when a smartphone knows to show the phone dialer keyboard instead of the QWERTY keyboard.

If you want to ignore "invalid" keypresses, you'll just have to do it the hard way:

const allowedKeysyms = [
  Clutter.KEY_KP_0,
  ...
  Clutter.KEY_KP_9,
  Clutter.KEY_0,
  ...
  Clutter.KEY_9,
  Clutter.KEY_colon,
];

entry.connect('key-press-event', (widget, event) => {
    if (!allowedKeysms.includes(event.get_key_symbol()))
        return Clutter.EVENT_STOP;

    return Clutter.EVENT_PROPAGATE;
});

Upvotes: 4

Related Questions