Gtk4下gtk-rs如何获取Gtk::Entry的用户输入内容?
在GTK4(gtk-rs)中获取Gtk::Entry的输入内容
我开发了一个小型gtk-rs应用,想要显示输入框并获取用户输入,但点击按钮时无法获取Gtk::Entry的输入内容。我知道需要在button.connect_clicked中处理,但不知道具体如何实现。
我的代码
build_ui方法
use gtk::prelude::*; use gtk::{Application, ApplicationWindow, Button, Orientation}; pub fn build_ui(app: &Application) { let button = Button::builder() .label("Submit") .margin_top(12) .margin_bottom(12) .margin_start(12) .margin_end(12) .build(); let input = gtk::Entry::builder() .placeholder_text("input") .margin_top(12) .margin_bottom(12) .margin_start(12) .margin_end(12) .build(); let gtk_box = gtk::Box::builder() .orientation(Orientation::Vertical) .build(); gtk_box.append(&input); gtk_box.append(&button); button.connect_clicked(move | _button| { println!("{}", input.display()); }); let window = ApplicationWindow::builder() .application(app) .title("gtk-app") .child(>k_box) .default_height(720) .default_width(360) .build(); window.present(); }
main.rs
const APP_ID: &str = "org.my-gtk-app"; fn main() { // Create a new application let app = Application::builder().application_id(APP_ID).build(); // Connect to "activate" signal of `app` app.connect_activate(home::build_ui); // Run the application app.run(); }
遇到的问题
- 尝试类似解决方案时,
.add方法报错:the following trait bounds were not satisfied: `ApplicationWindow: IsA<CellArea>` which is required by `ApplicationWindow: gtk4::prelude::CellAreaExt` - 编译器提示
Gtk::Entry没有.get_text()方法,GTK3中存在该方法但GTK4中没有 - 使用
.display()方法仅返回空字符串,无法获取用户输入
解决方案
在GTK4中,Gtk::Entry实现了Editable接口,需要通过EditableExt trait提供的text()方法获取输入内容。
修改按钮点击事件处理代码
将原有的connect_clicked回调替换为:
button.connect_clicked(move |_button| { let input_text = input.text(); println!("用户输入:{}", input_text); });
关键说明
- 确保已导入
gtk::prelude::*(你的代码已包含),EditableExt属于prelude扩展trait,导入后才能直接调用text()方法。 display()方法用于输出Entry对象的调试信息,并非获取用户输入,这是之前返回空字符串的原因。- 关于
.add方法报错:GTK4中容器添加子组件已从add改为append(针对Box等容器),你的代码中gtk_box.append(&input)的写法是正确的,之前的错误是误用了其他组件的add方法导致。
内容的提问来源于stack exchange,提问作者John554
相关产品推荐
相关产品推荐

