Lists and models
A list in Slint is shown from a model: the collection of data. When Rust changes the model (adds, removes or modifies an item), the interface updates by itself.
With StandardListView
Section titled “With StandardListView”The simplest way: a list of texts that can be selected. In the designer it’s List (StandardListView); its items are written in the panel, one per line, and the On selection change event tells you which item was chosen.
To change the items from Rust, the model is declared as a property:
import { Button, HorizontalBox, LineEdit, StandardListView, VerticalBox } from "std-widgets.slint";
export component AppWindow inherits Window { title: "Shopping"; width: 320px; height: 360px;
in property <[StandardListViewItem]> products; in-out property <int> chosen: -1; callback add(string); callback remove(int);
VerticalBox { HorizontalBox { padding: 0px;
new-item := LineEdit { placeholder-text: "Product"; accepted(text) => { root.add(text); self.text = ""; } }
Button { text: "Add"; clicked => { root.add(new-item.text); new-item.text = ""; } } }
StandardListView { model: root.products; current-item <=> root.chosen; }
Button { text: "Remove the chosen one"; enabled: root.chosen >= 0; clicked => { root.remove(root.chosen); } } }}use std::rc::Rc;
use slint::{Model, ModelRc, StandardListViewItem, VecModel};
slint::include_modules!();
fn main() -> Result<(), slint::PlatformError> { let ui = AppWindow::new()?;
// The model lives in Rust; the interface gets a reference (ModelRc). let products = Rc::new(VecModel::from(vec![StandardListViewItem::from("Bread"), StandardListViewItem::from("Milk")])); ui.set_products(ModelRc::from(products.clone()));
ui.on_add({ let products = products.clone(); move |text| { if !text.trim().is_empty() { products.push(StandardListViewItem::from(text.trim())); } } });
ui.on_remove({ let ui = ui.as_weak(); move |index| { if index >= 0 && (index as usize) < products.row_count() { products.remove(index as usize); ui.unwrap().set_chosen(-1); } } });
ui.run()}| In Rust | What it does |
|---|---|
VecModel::from(vec![…]) |
A model from a vector |
model.push(x) / remove(i) / insert(i, x) |
Add, remove and insert (the list updates) |
model.set_row_data(i, x) |
Change an item |
model.row_data(i) / row_count() / iter() |
Read (needs use slint::Model;) |
model.set_vec(new) |
Replace everything |
Rows your way: for
Section titled “Rows your way: for”To draw each item however you like (with a check box, a button, an icon…), define a struct and loop over the model
with for:
export struct Task { text: string, done: bool,}
// inside the component:in property <[Task]> tasks;
for task[i] in root.tasks: HorizontalBox { CheckBox { text: task.text; checked: task.done; } Button { text: "✕"; clicked => { root.delete(i); } }}In Rust the Task struct is generated by itself (with the same fields) and the model is a VecModel<Task>. The
To-do list sample is built this way, complete.
Next: Expressions and animations.