如何从按钮单击条目中获取信息?

时间:2019-10-27 19:47:15

标签: rust gtk-rs

我想从按钮单击的条目中获取输入,并在单击另一个按钮时显示该信息。这给我一个错误,因为闭包获得了我想在其中存储信息的firstname变量的所有权。

如何从条目中获取信息并重复使用?

// import gtk libs
extern crate gio;
extern crate gtk;

// declare use of gtk
use gtk::prelude::*;

fn main() {
    let mut firstname = String::new();

    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }
    let glade_src = include_str!("builder.glade");
    let builder = gtk::Builder::new_from_string(glade_src);

    let window: gtk::Window = builder.get_object("window1").unwrap();
    let buttonSubmit: gtk::Button = builder.get_object("buttonSubmit").unwrap();
    let buttonShow: gtk::Button = builder.get_object("buttonShow").unwrap();
    let entryFirstname: gtk::Entry = builder.get_object("entryFirstname").unwrap();

    // get information from entry
    buttonSubmit.connect_clicked(move |_| {
        firstname = entryFirstname.get_buffer().get_text();
    });

    // output information
    let firstname_clone = firstname.clone();
    buttonShow.connect_clicked(move |_| {
        println!("Firstname: {}", firstname_clone);
    });

    window.show_all();

    gtk::main();
}

1 个答案:

答案 0 :(得分:0)

一旦您的字符串已在闭包内移动,编译器将无法再静态地检查您是否不在混合对其的读写访问。您需要使用RefCell来启用读/写访问的运行时选择,可能与Rc结合使用以进行适当的内存管理:

let firstname = Rc::new(RefCell::new(String::new()));
let firstname_clone = firstname.clone();
// ...
buttonSubmit.connect_clicked(move |_| {
    firstname.replace(entryFirstname.get_buffer().get_text());
});
// ...
buttonShow.connect_clicked(move |_| {
    println!("Firstname: {}", firstname_clone.borrow());
});