4

I want to connect a handler to a custom signal. In my glade file I have a window with some buttons. The window is loaded like this in Rust:

let glade_src = include_str!("views/window.glade");
let builder = gtk::Builder::new_from_string(glade_src);
let window: gtk::ApplicationWindow = builder.get_object("Window").expect("Couldn't get window view");
window.set_application(Some(app));

A button in this window has this signal defined:

<signal name="clicked" handler="_on_start_clicked" swapped="no"/>

In Python I can connect using simple method annotations:

@Gtk.Template.Callback()
def _on_start_clicked(self, sender):
    print("start clicked")

But how can I connect a function in Rust to this signal?

AFAIK I don't have such annotations in Rust. I'd need something like window.connect_signal("_on_start_clicked", handler);

I'm using Rust and the gtk crate.

Michael
  • 2,528
  • 3
  • 21
  • 54

1 Answers1

3

This seems to be very new. The pull request is actually not in a stable release of gtk crate (as of v0.7.0). By using the git repo directly I managed to connect signals using Builder::connect_signals() like this:

// the handler
fn on_start_clicked(param: &[glib::Value]) -> Option<glib::Value> {
    println!("on_start_clicked fired!");
    None
}

// ...

// connect all signals
builder.connect_signals(|builder, handler_name| {
    match handler_name {
        // handler_name as defined in the glade file => handler function as defined above
        "_on_start_clicked" => Box::new(on_start_clicked),
        _ => Box::new(|_| {None})
    }
});

If still not in stable release use this dependency in Cargo.toml file:

[dependencies]
glib = { git = "https://github.com/gtk-rs/glib.git" }

[dependencies.gtk]
git = "https://github.com/gtk-rs/gtk.git"
features = ["v3_22"]
Michael
  • 2,528
  • 3
  • 21
  • 54
  • I know this was posted some time ago but have you worked out how to use the param argument for on_start_clicked? I cannot seem to get the gtk::ApplicationWindow out of [glib::Value]. – Galo do Leste Feb 10 '23 at 03:03