表达式是在用户界面中声明关系和连接的一种强大方式。它们通常用于将基本算术与其他元素的属性访问结合起来。当这些属性发生变化时,表达式会自动重新求值,并将新值分配给表达式关联的属性:
slint
export component Example { //声明一个 int类型的属性 in-out property<int> my-property;
//访问该属性 width: root.my-property *20px;
}当 my-property发生变化时,宽度也会自动变化。
带有数字的表达式中的算术运算与大多数编程语言中的运算类似,使用运算符 *、+、-、/:
slint
export component Example { in-out property <int> p:1 *2 +3 *4; // 等同于 (1 *2)+(3 *4)}使用 + 连接字符串。
运算符 && 和 || 表示布尔值之间的逻辑与和或。运算符 ==、!=、>、<、>= 和 <= 比较相同类型的值。
通过使用元素的名称后跟 . 和属性名来访问元素的属性:
slint
export component Example { foo := Rectangle { x:42px; } x: foo.x;}也支持三元运算符 ... ? ... : ...,与 C 或 JavaScript 类似:
slint
export component Example inherits Window { preferred-width:100px; preferred-height:100px;
Rectangle { touch := TouchArea {} background: touch.pressed ? #111: #eee; border-width:5px; border-color: !touch.enabled ? #888: touch.pressed ? #aaa: #555; }}语句
let 语句(局部变量)
let关键字可用于创建局部变量。局部变量是不可变的,不能重新声明(即使在其他作用域中)。它们可以选择性地具有类型注解。
slint
clicked => { let foo = "hello world"; // 无类型注解,类型被推断 debug(foo); //打印 "hello world"
let bar: int =2; //显式类型注解 debug(bar); //打印 "2"}###赋值
slint
clicked => { some-property =42; }使用 += -= *= /= 进行自赋值
slint
clicked => { some-property +=42; }调用回调
slint
clicked => { root.some-callback(); }###条件语句
slint
clicked => { if (condition) { foo =42; } else if (other-condition) { bar =28; } else { foo =4; }}空表达式
slint
clicked => { }// 或clicked => { ; }