orbtk的api在2019.2进行了修改,该文章为2018版
新版请转[新版orbtk gui基础]
orbtk helloworld
我们在上一节的代码中加入一个helloworld的label:
use orbtk::*;
fn main() {
let mut application = Application::default();
//创建一个textblock,添加一个Label类型的属性
let text_block=TextBlock::create()
.with_property(Label::from("Hello, World!"));
//创建root控件,把textBlock设置为子控件
let root=Template::default()
.as_parent_type(ParentType::Single)
.with_child(text_block);
application
.create_window()
.with_bounds(Bounds::new(100, 100, 320, 210))
.with_title("OrbTk - helloworld")
.with_resizable(true)//可以调整窗口大小
.with_root(root)
//.with_debug_flag(true)
.build();
application.run();
}
cargo run运行后界面如下:
注意:
- TextBlock的定义是:
pub struct TextBlock;
- 但是
TextBlock::create()
函数返回的是一个Template - .with_property()是Template的函数,返回self,类型是Template
- Label是一个属性(Property),不是一个控件(widget)
- root控件定义时必须调用as_parent_type()函数设置ParentType属性
parent_type
是什么,root为什么必须要设置呢?
parent_type
是Template的一个成员,类型为ParentType,它指示Template控件能够添加子控件的个数。
ParentType定义为:
pub enum ParentType {
None,//表示不能添加子控件
Single,//只能添加一个子控件
Multi,//可以添加多个子控件
}
当添加子控件到一个widget template时。
- 如果
parent_type
为ParentType::None
,则函数自动跳过,什么也不添加 - 如果
parent_type
为ParentType::Single
,则只能添加一个子控件,如果已经有一个子控件,则覆盖/替换 - 如果
parent_type
为ParentType::Multi
,则可以添加任意多个子控件到当前控件的Template
所以,在添加子控件之前必须设置parent_type
。事实上orbtk内建的控件都有默认的parent_type值,比如row,colomn等默认为Multi,Button等默认为Single。
使用链式调用方法
orbtk的属性设置,控件(widget)创建都是支持链式调用的,所以像text_block等不需要绑定到变量上,代码看上去也更减短。如下代码与上节helloworld代码效果完全相同
use orbtk::*;
fn main() {
let mut application = Application::default();
let root = Template::default()
.as_parent_type(ParentType::Single)
.with_child(TextBlock::create().with_property(Label::from("Hello, World!")));
application
.create_window()
.with_bounds(Bounds::new(100, 100, 320, 210))
.with_title("OrbTk - helloworld")
.with_resizable(true)
.with_root(root)
//.with_debug_flag(true)
.build();
application.run();
}
本文代码
本文代码在https://github.com/hustlei/RustGuiOrbtkTutorial
可以使用cargo run --bin helloworld
命令编译运行