我正在尝试使用 gtk4 绑定来学习 rust,并决定尝试ListStore
作为ListBox
. 为了绑定模型,Widget
需要返回的函数,但我需要一个Label
. 为什么Label
继承Widget
(实现IsA<Widget>
)的不满足Widget
类型?
错误:
error[E0308]: mismatched types
--> src/main.rs:22:5
|
21 | fn create_widget<'r>(label: &'r Object) -> Widget {
| ------ expected `gtk4::Widget` because of return type
22 | Label::new(Some(label.property_value("name").get().unwrap()))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `gtk4::Widget`, found struct `gtk4::Label`
完整代码:
use gtk::prelude::*;
use gtk::{Application, ApplicationWindow, Paned, Label, Orientation, ListBox, ListBoxRow, Widget};
use gtk::gio::ListStore;
use gtk::glib::Type;
use gtk::glib::Object;
fn main() {
println!("Hello, world!");// Create a new application
let app = Application::builder()
.application_id("org.gtk-rs.example")
.build();
// Connect to "activate" signal of `app`
app.connect_activate(build_ui);
// Run the application
app.run();
}
fn create_widget<'r>(label: &'r Object) -> Widget {
Label::new(Some(label.property_value("name").get().unwrap()))
}
fn build_ui(app: &Application) {
let listbox_left = ListBox::new();
let listbox_right = ListBox::new();
let list_model = ListStore::new(Type::STRING);
listbox_right.bind_model(Some(&list_model), create_widget);
let paned = Paned::builder()
.start_child(&listbox_left)
.end_child(&listbox_right)
.orientation(Orientation::Horizontal)
.build();
// Create a window
let window = ApplicationWindow::builder()
.application(app)
.title("My GTK App")
.child(&paned)
.build();
for n in 1..11 {
let n_as_string =(n as u32).to_string();
let mut my = String::from("Left:");
my.push_str(&n_as_string);
let m = Object::with_values(Type::STRING, &[("name", my.to_value())]);
list_model.append(&m.unwrap());
}
// Present window
window.present();
}