FAQ - Help and questions

How do I build a first window with Slint and connect a button to Rust code?

#slint#gui#desktoppublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Describe the window in Slint's markup, inline with the slint! macro or in a .slint file, then create it from Rust, set properties, and register callbacks with on_ methods. A weak handle lets a callback reach the window without keeping it alive. The example follows the Slint documentation and was not compiled here.

Checked with not compiled here. The code follows the Slint 1.18 documentation (docs.slint.dev); a Slint build was skipped because its dependency tree needs several GB of disk and a newer rustc than the one installed. Check it with your own Slint version.

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A Slint window has two halves. The markup says what the window looks like and which properties and callbacks it has. The Rust code creates the window, reads and writes the properties, and runs code when a callback fires.

Cargo.tomltoml
[dependencies]
slint = "1.18"
src/main.rsrust
slint::slint! {
    export component MainWindow inherits Window {
        in-out property <int> counter: 0;
        callback clicked();
        VerticalLayout {
            padding: 20px;
            spacing: 10px;
            Text { text: "Clicked " + root.counter + " times"; }
            Button { text: "Click me"; clicked => { root.clicked(); } }
        }
    }
}

fn main() -> Result<(), slint::PlatformError> {
    let window = MainWindow::new()?;
    let weak = window.as_weak(); // a handle that does not keep the window alive
    window.on_clicked(move || {
        if let Some(w) = weak.upgrade() {
            w.set_counter(w.get_counter() + 1);
        }
    });
    window.run()
}

This sample was not compiled for this thread; compare it with the examples in the Slint documentation for your version.

The names come from the markup: the property counter gives get_counter and set_counter, and the callback clicked gives on_clicked and invoke_clicked. For anything beyond a few lines, put the markup in a .slint file and compile it from build.rs with the slint-build crate, so you get editor support for the markup.

Common mistakes#

  • Capturing the window itself in the callback. That makes the window own a closure that owns the window. Use as_weak() and upgrade(), as above.
  • Ignoring the licence. Slint has GPL-3.0, royalty-free and commercial options; see the toolkit overview thread.

Do I have to learn a second language?#

Yes, a small one: the Slint markup. In exchange the layout is declarative and separate from your Rust logic.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet