How to set member callback function


#1

hi, im using gtk-rs to write a gui application

extern crate gtk;

use gtk::traits::*;
use gtk::signal::Inhibit;

struct Test {
    window: gtk::Window,
}


impl Test {

    fn new() -> Option<Test> {
	let window = gtk::Window::new(gtk::WindowType::Toplevel).unwrap();
	let button = gtk::Button::new_with_label("button").unwrap();
	let layout = gtk::Box::new(gtk::Orientation::Vertical, 5).unwrap();

	button.connect_clicked(callback); // how to do this ?

	layout.add(&button);
	window.add(&layout);
	window.show_all();

	Some(Test {
	    window: window,
	})
    }

    fn callback(&self, _: gtk::Button) {
	println!("button clicked!");
    }
}

fn main() {
    gtk::init();

    let t = Test::new().unwrap();

    gtk::main();
}

i want to connect a callback to member function, because i need to use “window” variable in Test struct.


#2

Callbacks can be any function satisfying the signature (in this case being a function that takes a Button as an argument), just pass the function’s name. If you want to also pass some information you just calculated you can use a closure. Closures are explained in The Book’s chapter on closures