我正在学习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
告诉您正在调用(调用(该方法,并且它没有结果 (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);
}