2017-04-03 9 views
1

私は、基本OSで提供されているVala GTK + 3チュートリアルを進めています。このコードは、GTKボタンのクリックされたアクションにカスタム関数をどのように接続すればよいですか?

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

はラムダ機能を使用して、クリックするとボタンのラベルを変更することを理解しています。私がコンパイルしようとすると、コンパイル

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

しかし、私はヴァラから、このエラーを取得:私はこれを試してみた

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

:私は何をしたいの代わりに、この関数を呼び出している

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) 

私はとても優しくしてくださいヴァラとLinuxの両方に新しいです誰かが正しい方向に私を指すことができますか?

答えて

4

あなたは関数への参照ではなく、関数の結果を渡す必要があります。だから、それは次のようになります。ボタンをクリックすると

button.clicked.connect (clicked_button);

GTK +は、引数としてボタンでclicked_button関数を呼び出します。

エラーメッセージinvocation of void method not allowed as expressionあなたは(呼び出し)メソッドを呼び出しているし、それが結果(ボイド)持っていないあなたを語っています。関数名の末尾に括弧(())を追加すると、その関数が呼び出されます。

+0

常に最初の引数として関数に渡される信号を発するインスタンスをしていますか?これはすべてのGTKウィジェットで同じですか? – Garry

+0

はい、コールバックにはGtkCallbackの関数シグネチャが必要です。これはCではvoid(* GtkCallback)(GtkWidget * widget、gpointer data)です。 https://developer.gnome.org/gtk3/stable/GtkWidget.html#GtkCallbackおよびhttps://valadoc.org/gtk+-3.0/Gtk.Callback.htmlを参照してください。ユーザデータ部分は通常、メソッドが定義されているクラスインスタンスか、コールバックが関数名またはラムダ式として渡されたかどうかに応じてクロージャになるため、Valaでは隠されます。 – AlThomas

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); 
} 
関連する問題