rustslint

How to properly access the properties of the child elements of the Slint component in Rust?


I have this in .slint file

import { HorizontalBox , LineEdit} from "std-widgets.slint";

export component MainWindow inherits Window {
    callback line_edit_edited();
    HorizontalBox {
        LineEdit {
            edited => {
                root.line_edit_edited();
            }
        }
    }
}

And I want to access text property of LineEdit.

slint::include_modules!();

fn main() -> Result<(), slint::PlatformError> {
    let ui = MainWindow::new()?;
    ui.on_line_edit_edited(move || {
        println!("Edited text /* How to get text from LineEdit here? */");
    });

    ui.run()
}

I know that for this purpose can be used bindings or singleton as described in https://stackoverflow.com/a/76760315. But what if we will have hundreds of properties? They all will be accessible from the root, I think this is not a good solution. Don't we have other ways?


Solution

  • You can not access properties that are not in the root element. You can define your callback to take a string argument though, turning the callback line into

        callback line_edit_edited(string);
    

    and then define your LineEdit like this:

            LineEdit {
                edited => {
                    root.line_edit_edited(self.text);
                }
            }
    

    The rust side will then look like this:

        ui.on_line_edit_edited(move |edited| {
            println!("Edited text is: {edited}");
        });
    

    You can of course pass more arguments that way and could e.g. include an ID and recycle the same callback for different LineEdits. The rust code can then use the ID to find out which line edit triggered the callback.

    When you have hundreds of properties, then you are better of defining a custom model and let that drive parts of the UI. You will need to implement the Model trait to do so.

    I hope this helps:-)