Write custom component in Rust to be available in Slint #2267
Replies: 1 comment
-
Unfortunately we don't support custom components written Rust yet :(. This is on our TODO though. Converting your pure Rust data structures to Slint exposed structures on the fly is the way to go right now, I think. We do something like that for example in the energy monitor: This works for simple structs. But you can do the same for entire data models where you have additional state in Rust that doesn't fit into the displayed data, by using a mapping model. Suppose you have your own data structure like his: pub struct ForecastDay {
pub date: String,
pub date_epoch: i64,
pub day: Day,
pub astro: Astro,
pub hour: Vec<Hour>
} and you want to have a model of that data structure and maintain it, but at the same time show some fields in Slint. Then you can put the above first into a regular data model, for example a let forecast_model: Rc<slint::VecModel<ForecastDay>> = Rc:new(slint::VecModel::from(vec![ForecastDay { ... }])); and then expose parts of it in Slint: export struct ForecastDisplay {
day: string,
location: string,
}
...
export component App := Window {
property <[ForecastDisplay]> forecast;
VerticalLayout {
for weather[i] in forecast: Text {
text: "Day: \{weather.day}";
}
}
} The connection between the Slint ForecastDisplay and the Rust Forecast is done with a mapping model: let forecast_display_model = forecast_model.clone().map(|rust_forecast| { ForecastDisplay{ day: rust_forceast.day.into(); ... } });
app.set_forecast(forecast_display_model); This means that the Rust data structures are converted on-the-fly to the Slint data structures and any changes you make to the underlying forecast_model - that can contain totally Rust specific things - are automatically mapped to the user interface. The map model takes care of that. |
Beta Was this translation helpful? Give feedback.
-
Hi there!
I am just learning Slint, it is amazing in a way how quickly I can create very pretty interfaces!
However the app I am working on is doing some IO and has some state, which is not really mappable into Slint type system, and Rust also makes it quite painful to have global state.
If I could implement a component in pure Rust then the problem would go away as all the state elements are mapped into Slint structs for display purposes, but I cannot find any examples on how to do that 🤔 could someone please point me to an example where the component is declared in Rust and is available in Slint?
Alternatively, if I could attach
Arc
with custom generic to a component that could be a workaround, so I could pass it around in callbacks, but I don't see a way to do that either 🤔Beta Was this translation helpful? Give feedback.
All reactions