javascript – GJS:Gtk.TextView按键事件不起作用

我正在尝试使用gjs为gnome- shell创建简单的gtk应用程序.

它的窗口只包含Gtk.TextView,我想在用户输入时处理事件.

这是我的代码

#!/usr/bin/gjs

var Gtk = imports.gi.Gtk;

function MainWindow () {
    this._init ();
}

MainWindow.prototype = {
    _init: function () {
        this.window = new Gtk.Window ({
            title: "Just Calculator",window_position: Gtk.WindowPosition.CENTER,default_height: 400,default_width: 440,});

        //this.window.show ();
        this.window.connect ("hide",Gtk.main_quit);
        this.window.connect ("delete-event",function () {
            Gtk.main_quit();
            return true;
        });

        this.textBox = new Gtk.TextView();
        this.textBox.connect('key-press-event',this._keyPress);

        var sw = new Gtk.ScrolledWindow ({shadow_type:Gtk.ShadowType.IN});
        sw.add (this.textBox);
        this.window.add(sw);

        this.window.show_all();
    },_keyPress: function(textview,event) {
        print(event,event.type,event.keyval);
        textview.buffer.text = 'ok';
        return true;
    }
}

Gtk.init (null,null);
var window = new MainWindow ();
Gtk.main ();

它通常工作,但我无法读取event.keyval:控制台输出是“未定义”:

[union instance proxy GIName:Gdk.Event jsobj@0x7f99b1027040 native@0x1dfeab0] undefined undefined

有人能告诉我我做错了什么吗?
谢谢!

解决方法

Gdk.Event不包含属性类型或keyval,这就是它们未定义的原因.它已经存在很长时间了,但现在有文件可用于GObject Introspection绑定到 https://people.gnome.org/~gcampagna/docs的Gjs.

从你的打印出来,你看到该事件是一个Gdk.Event,其文档是在https://people.gnome.org/~gcampagna/docs/Gdk-3.0/Gdk.Event.html.在那里你可以看到有函数get_event_type和get_keyval.第一个返回Gdk.EventType(https://people.gnome.org/~gcampagna/docs/Gdk-3.0/Gdk.EventType.html),后者返回第二个元素包含按下的键的数字代码的数组.您可以将数字键与clutter中以KEY_开头的常量进行比较.

例如,在代码顶部添加一些导入

var Gdk = imports.gi.Gdk;
var clutter = imports.gi.clutter;

并将记录行更改为

print(event,event.get_event_type() === Gdk.EventType.KEY_PRESS,event.get_keyval()[1] === clutter.KEY_Escape);

获得一些合理的输出.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...