Hello World App¶
Keywords: iced::Sandbox, iced::Settings, iced::widget::text
创建项目¶
首先,创建一个新的 Rust 项目,并添加对iced库的依赖。
cargo new text-editor
cd text-editor
cargo add iced
此时的main.rs文件内容如下:
fn main() {
println!("Hello, world!");
}
创建GUI应用¶
iced的GUI类有Application和Sandbox两种。其中Sandbox是一个简化版的Application,提供了一些默认的行为。Sandbox特性包含如下方法:
pub trait Sandbox {
type Message: std::fmt::Debug + Send;
fn new() -> Self;
fn title(&self) -> String;
fn update(&mut self, message: Self::Message);
fn view(&self) -> Element<'_, Self::Message>;
fn theme(&self) -> Theme {
Theme::default()
}
fn style(&self) -> theme::Application {
theme::Application::default()
}
fn scale_factor(&self) -> f64 {
1.0
}
fn run(settings: Settings<()>) -> Result<(), Error>
where
Self: 'static + Sized,
{
<Self as Application>::run(settings)
}
}
为了使用Sandbox,我们需要实现其中未实现的方法,即Message、new、title、update和view。
-
Message是一个枚举类型,用于定义应用会产生的消息类型,需要实现std::fmt::Debug和Send特性。#[derive(Debug)] // Inherit the Debug trait enum Message {} // No message required -
new方法用于创建一个新的Sandbox实例,初始化实例状态,一般情况下直接返回Self即可。fn new() -> Self { Self } -
title方法用于返回GUI窗口的标题。fn title(&self) -> String { String::from("A text editor") } -
update方法和view方法共同组成应用的消息循环:update方法用于处理消息,更新应用状态,view方法用于在状态更新后更新应用界面。此处我们在view方法中放置一个文本控件。fn update(&mut self, message: Self::Message) { match message { // No message to handle } } fn view(&self) -> Element<'_, Self::Message> { text("Hello, world!").into() }
通过Sandbox::run方法启动应用,该方法返回Result<(), Error>类型,可以直接作为main函数的返回值。
以下为完整的main.rs文件内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |