Slint 的所有組件都可顯式指定或通過布局約束關系來渲染組件。
幾何屬性
- 位置屬性: 位置屬性名為
x
和y
,通??娠@示指定其值,也可通過表達式計算動態值, 其值為相對父組件的位置,而非相對屏幕的絕對位置。 - 大小屬性: 大小屬性可由多個屬性指定或限制
width
,height
preferred-width
,preferred-height
:用于指定優先渲染的大小,最終效果可能不為次值。min-width
,min-height
,max-width
,max-height
:用于限制最大和最小適應范圍
集合屬性可由兩種單位表示:
- 物理像素: 使用
phx
作為值的后綴,推薦使用 - 邏輯像素: 使用
px
作為值的后綴
對于大小的屬性指定,可直接使用值來指定,也可使用X%
表示該屬性為父屬性的占比。如 width: 50%
表示寬度為父節點寬度的一半。示例如下:
export component Example inherits Window {
width: 800px;
height: 480px;
background: blue;
Rectangle {
x: 100px;
y: 10px;
width: parent.width/2;
height: 80%;
background: red;
Rectangle {
x: root.x + 100px;
y: root.y + 100px;
width: 100px;
height: 100px;
background: green;
}
}
}
image.png?x-oss-process=image/watermark,g_center,image_YXJ0aWNsZS9wdWJsaWMvd2F0ZXJtYXJrLnBuZz94LW9zcy1wcm9jZXNzPWltYWdlL3Jlc2l6ZSxQXzQwCg==,t_20
布局類組件
通常對于控件節點較多的界面,如果指定所有組件的位置和大小,則相對繁瑣,且不便于修改。在設計中通常根據 GUI 的層級關系和對齊關系,可使用自動布局的屬性,根據 Layout 的特性,讓渲染器自動計算出合適的位置和大小。Slint 支持三種基本的布局組件來自動約束節點的位置和大小。
VerticalLayout
: 豎直方向依次布局子組件HorizontalLayout
: 水平方向依次布局子組件GridLayout
: 網格方式依次布局子組件.
測試代碼如下:
import { HorizontalBox } from "std-widgets.slint";
export component Example inherits Window {
width: 800px;
height: 480px;
background: green;
HorizontalLayout {
VerticalLayout {
horizontal-stretch: 2;
spacing: 10px;
Rectangle {
background: red;
}
Rectangle {
background: yellow;
}
}
VerticalLayout {
Rectangle {
background: blue;
}
Rectangle {
background: blueviolet;
}
Rectangle {
GridLayout {
Rectangle {
background: gold;
}
Rectangle {
background: gainsboro;
}
Rectangle {
row: 2;
background: goldenrod;
}
Rectangle {
row: 2;
col: 2;
background: royalblue;
}
}
}
}
}
}
各組件有其他屬性可指定大小和起始位置的計算規則,如
spacing
: 指定子組件之間的間隔
padding
:指定子組件相隔父組件邊框的間隔alignment
:指定子組件的對齊方式
例子如下:
import { HorizontalBox } from "std-widgets.slint";
export component Example inherits Window {
width: 800px;
height: 480px;
background: green;
HorizontalLayout {
VerticalLayout {
spacing: 10px;
padding: 10px;
Rectangle {
background: red;
}
Rectangle {
background: yellow;
}
}
VerticalLayout {
alignment: LayoutAlignment.center;
Rectangle {
background: blue;
height: 30%;
}
Rectangle {
height: 40%;
background: blueviolet;
}
}
}
}