[英]How can I change button label within its own callback in FLTK?
I want to change button's label when button is pressed.我想在按下按钮时更改按钮的 label。 But I got this error message.但是我收到了这个错误信息。
error[E0505]: cannot move out of `but` because it is borrowed
--> src/main.rs:24:22
|
24 | but.set_callback(move || but.set_label("PRESSED"));
| --- ------------ ^^^^^^^ --- move occurs due to use in closure
| | | |
| | | move out of `but` occurs here
| | borrow later used by call
| borrow of `but` occurs here
error: aborting due to previous error
The code itself代码本身
1 use fltk::*;
2
3 fn main() {
4
5 let app = app::App::default().with_scheme(app::Scheme::Gleam);
6 let mut win = window::Window::default()
7 .with_pos(0, 0)
8 .with_size(300, 300)
9 .with_label("FLTK_Window");
10 let mut but = button::Button::default()
11 .with_pos(0, 0)
12 .with_size(100, 50)
13 .center_of(&win)
14 .with_label("BUTTON");
15 win.end();
16 win.show();
17
18 win.set_color(Color::Black);
19 but.set_color(Color::from_rgb(0, 100, 0));
20 but.set_label_color(Color::White);
21 but.set_label_type(LabelType::Normal);
22 but.set_callback(move || but.set_label("PRESSED"));
23 app.run().unwrap();
24 }
How I cand handle with such type of problem?我该如何处理这类问题?
The simplest solution is to clone
but
before setting the callback and then moving it into the closure like so:最简单的解决方案是clone
but
在设置回调之前,然后将其移动到闭包中,如下所示:
use fltk::*;
fn main() {
let app = app::App::default().with_scheme(app::Scheme::Gleam);
let mut win = window::Window::default()
.with_pos(0, 0)
.with_size(300, 300)
.with_label("FLTK_Window");
let mut but = button::Button::default()
.with_pos(0, 0)
.with_size(100, 50)
.center_of(&win)
.with_label("BUTTON");
win.end();
win.show();
win.set_color(Color::Black);
but.set_color(Color::from_rgb(0, 100, 0));
but.set_label_color(Color::White);
but.set_label_type(LabelType::Normal);
but.clone().set_callback(move || but.set_label("PRESSED"));
app.run().unwrap();
}
In addition to frankenapps answer, fltk has an overloaded set_callback method (set_callback2) which gives you access to a mutable reference of the widget.除了 frankenapps answer,fltk 有一个重载的 set_callback 方法 (set_callback2),它使您可以访问小部件的可变引用。
but.set_callback2(|b| b.set_label("PRESSED"));
You can also use move
to capture outer variables if you need to.如果需要,您还可以使用move
来捕获外部变量。
Update: Since fltk-rs version 1.0, set_callback captures &mut self by default.更新:从 fltk-rs 1.0 版开始,set_callback 默认捕获 &mut self。
but.set_callback(|b| b.set_label("PRESSED"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.