繁体   English   中英

如何将自定义功能连接到GTK按钮的单击操作?

[英]How do I connect a custom function to the clicked action of a GTK Button?

我正在通过Elementary OS提供的Vala GTK + 3教程。 我明白这段代码:

var button_hello = new Gtk.Button.with_label ("Click me!");
button_hello.clicked.connect (() => {
    button_hello.label = "Hello World!";
    button_hello.set_sensitive (false);
});

使用Lambda函数在单击按钮时更改按钮的标签。 我想要做的是改为调用此函数:

void clicked_button(Gtk.Button sender) {
    sender.label = "Clicked. Yippee!";
    sender.set_sensitive(false);
}

我试过这个:

button.clicked.connect(clicked_button(button));

但是当我尝试编译时,我从Vala编译中得到了这个错误:

hello-packaging.vala:16.25-16.46: error: invocation of void method not allowed as expression
    button.clicked.connect(clicked_button(button));
                           ^^^^^^^^^^^^^^^^^^^^^^
Compilation failed: 1 error(s), 0 warning(s)

我是Vala和Linux的新手,所以请保持温和,但有人可以指出我正确的方向吗?

您需要传递对函数的引用,而不是函数的结果。 所以它应该是:

button.clicked.connect (clicked_button);

单击该按钮时,GTK +将以按钮作为参数调用clicked_button函数。

invocation of void method not allowed as expression的错误消息invocation of void method not allowed as expression告诉您正在调用(调用)该方法,并且它没有结果(void)。 将括号()添加到函数名称的末尾将调用该函数。

管理以使其工作。 以下是其他人需要的代码:

int main(string[] args) {
    //  Initialise GTK
    Gtk.init(ref args);

    // Configure our window
    var window = new Gtk.Window();
    window.set_default_size(350, 70);
    window.title = "Hello Packaging App";
    window.set_position(Gtk.WindowPosition.CENTER);
    window.set_border_width(12);
    window.destroy.connect(Gtk.main_quit);

    // Create our button
    var button = new Gtk.Button.with_label("Click Me!");
    button.clicked.connect(clicked_button);

    // Add the button to the window
    window.add(button);
    window.show_all();

    // Start the main application loop
    Gtk.main();
    return 0;
}

// Handled the clicking of the button
void clicked_button(Gtk.Button sender) {
    sender.label = "Clicked. Yippee!";
    sender.set_sensitive(false);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM