gtk-rs / examples

DEPRECATED, use https://github.com/gtk-rs/gtk-rs repository instead!
MIT License
283 stars 76 forks source link

Add an example with mutable state #300

Open David-OConnor opened 4 years ago

David-OConnor commented 4 years ago

I'm not sure how to go about adding mutable shared state. I feel like this is a very common thing to want in a UI app, but I can't find it in the examples. I'm suspicious the solution involves Rc<RefCell<T>>, but am not sure how to do it. Eg:

let state = Rc::new(RefCell::new(state));  // Interior mutability to solve this?

let btn1 = Button::new_with_label("1");
btn1.connect_clicked(|_| {
    state.borrow_mut().value1 = true;
 });

let btn2 = Button::new_with_label("2");
btn2.connect_clicked(|_| {
    state.borrow_mut().value2 = true;
});
piegamesde commented 3 years ago

That's pretty much how you do it, yes.