antoyo / relm

Idiomatic, GTK+-based, GUI library, inspired by Elm, written in Rust
MIT License
2.43k stars 78 forks source link

How to close popup by a button click? #212

Closed MGlolenstine closed 4 years ago

MGlolenstine commented 4 years ago

I'm unsure on how to close a popup window from within, as I cannot use the connect_clicked with self to get the window object. Whenever a person clicks on the "Ok" button, I'd like to close the popup. I've already tried using

button.connect_clicked( |c| {
    self.window.close();
});

but it doesn't work, as it says that it can't use the self, because it's not static.

This is the snippet of my widget.

    fn init_view(&mut self) {
        match self.model.buttons{
            ButtonsType::Ok => {
                let button = gtk::Button::new();
                button.set_label("Ok");
                button.set_vexpand(true);
                button.connect_clicked(|c| {
                    // CLOSE THE POPUP
                });
                self.buttons.add(&button);
                button.show_all();
                println!("Adding an OK Button!");
            },
            _ => {}
        }
    }

    view! {
        #[name="window"]
        gtk::Window(gtk::WindowType::Popup){
            property_default_width: 480,
            property_default_height: 272,
            decorated: true,
            resizable: true,
            position: gtk::WindowPosition::Center,
            gtk::Box{
                orientation: Vertical,
                gtk::Box{
                    vexpand: true,
                    orientation:Horizontal,
                    #[name="image"]
                    gtk::Image{
                        vexpand: false,
                    },
                    #[name="text"]
                    gtk::Label {
                        label: &self.model.message,
                        vexpand: false,
                        hexpand: true,
                        text: &self.model.message,
                    },
                },
                #[name="buttons"]
                gtk::Box{
                    orientation: Horizontal,
                    property_height_request: 100,
                    vexpand: true,
                    hexpand: true,
                }
            }
        }
    }
antoyo commented 4 years ago

You have to clone the window before you move it into the closure:

let window = self.window.clone();
button.connect_clicked(move |c| {
    window.close();
});

There's also a clone! macro in glib to take care of this.

MGlolenstine commented 4 years ago

clone! macro and the above code did solve my problem

Thanks!