用戶界面由 Slint 語言編寫,并保持在.slint
格式的文本文件中。每個.slint
文件可定義一個或多個組件,通過調用這些組件聲明形成一個組件樹,這些節點組件構成了界面的框架。您可以重復使用某些控件,也可以遞歸調用或繼承的方式生成新的組件。如下展示了一個簡單的 GUI 界面組件的代碼:
import { Button } from "std-widgets.slint";
component MyRectangle inherits Rectangle {
in property name: "EmbeddedTeckTalk";
Text {
text: root.name;
}
}
export component MyApp inherits Window {
height: 320px;
width: 280px;
VerticalLayout {
alignment: LayoutAlignment.start;
width: parent.width;
Rectangle {
height: 100px;
background: green;
Text {
text: "Hello Slint";
}
}
MyRectangle{
// width: 100px;
height: 100px;
}
MyRectangle {
// width: 100px;
height: 100px;
name: "Slint";
}
}
}
以上代碼中,MyRectangle
和MyApp
都是自定義的組件,其中MyRectangle
繼承了Slint 內置的Rectangle
組件庫,意味著MyRectangle
直接繼承了Rectangle
的所有屬性,同時,MyRectangle
也將Slint
的Text
包含到內部子節點,因此擁有了一個Text
對象。MyApp
則繼承Window
組件,則可以作為該 GUI 節點的根節點,因此可以用來作為 GUI 的顯示入口組件。MyApp
內部聲明了多個組件,通過組件和屬性聲明各子節點組件的位置、從屬、約束等關系。各組件通過屬性綁定固定的值,也可通過接口或表達式綁定動態變化的值,Slint
會自動計算表達式或依賴的變化, 因此組件屬性值的變化能自動傳導并更新所有依賴該屬性的節點。渲染效果如下所示
各子組件也可以使用:=
語法來指定對象名,如下示例所示:
export component MyApp inherits Window {
width: 200px;
height: 200px;
in property name: "EmbeddedTechTalk";
// 這是一行注釋
rec := Rectangle {
background: red;
width: root.width;
height: self.width;
border-radius: self.width/2;
border-color: red;
/* 注釋
這是一個注釋
*/
VerticalLayout {
alignment: LayoutAlignment.space-between;
txt1 := Text{
text: root.name;
width: rec.width;
horizontal-alignment: center;
font-size: 15px;
}
txt2 := Text{
text: "Hello world";
width: parent.width;
}
}
}
}
子組件對象的命名規范如下:
- 可由字母(a-zA-Z)、數字、下劃線(_)、破折號(-)組成
- 不能以數字開頭
- 下劃線(_)、破折號(-)可互換,因此命名如
top_rec
和top-rec
為同一個對象名。
同時 Slint 保留以下三個作為預定義的命名,有特殊含義,因此新的對象不能指定以下三個作為對象名。
- root: 該組件的根節點組件引用
- self: 當前組件的引用
- parent: 當前組件的父節點的引用
Slint 文件注釋支持以下兩種,與 C語言注釋完全一樣
- 單行注釋
//
: 只在當前行中標記注釋文字 - 多行注釋
/* ... */
:將多行注釋包含到注釋塊
以上slint
代碼渲染如下: