3

我正在学习 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 的新手,所以请保持温和,但有人能指出我正确的方向吗?

4

2 回答 2

5

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

button.clicked.connect (clicked_button);

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

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

于 2017-04-03T15:12:55.087 回答
0

设法让它工作。这是其他人需要的代码:

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);
}
于 2017-04-03T15:11:12.363 回答