Skip to content

类型转换

Slint 支持不同类型之间的转换。显式 转换是必需的,以使 UI 描述更健壮,但为方便起见, 某些类型之间允许隐式转换。

可以进行以下转换:

  • int 可以隐式转换为 float,反之亦然。 从 float 转换为 int 时,值会被截断。
  • int 和 float 可以隐式转换为 string, 而 string 可以通过 to-float() 成员函数转换为 float。 参见数字与字符串之间的转换。
  • physical-length、relative-font-size 和 length 只有在已知像素比的情况下 才能隐式地相互转换。
  • 单位类型(length、physical-length、duration、……)不能转换为数字(float 或 int), 但它们可以除以自身而得到数字。类似地,数字可以乘以其中一种 单位。其思路是通过乘以 1px 或除以 1px 来进行此类转换
  • 字面量 0 可以转换为任何这些带关联单位的类型。
  • 当结构体类型共有的字段可以转换时,结构体类型会转换为另一种结构体类型。 缺失的字段取其默认值,多余的字段会被丢弃并发出警告。 同时出现两者是一个错误,因为这很可能是笔误。
  • 数组通常不相互转换。如果元素类型可转换,则数组字面量可以转换。
export component Example {
// OK: int converts to string
property<{a: string, b: int}> prop1: {a: 12, b: 12 };
// OK: even if a is missing, it will just have the default value ("")
property<{a: string, b: int}> prop2: { b: 12 };
// OK, with a warning: the extra c is discarded
property<{a: string, b: int}> prop3: { a: "x", b: 12, c: 42 };
// ERROR: b is missing and c is extra, this doesn't compile, because it could be a typo.
// property<{a: string, b: int}> prop4: { a: "x", c: 42 };
// OK: no field listed, so each one takes its default value
property<{a: string, b: int}> prop5: {};
property<string> xxx: "42.1";
property<float> xxx1: xxx.to-float(); // 42.1
property<bool> xxx2: xxx.is-float(); // true
property<int> xxx3: 45.8; // 45
}
slint

int 和 float 隐式转换为 string。 要控制结果中出现多少位数字,请使用 to-fixed() 和 to-precision() 成员函数,而不是隐式转换。 要不考虑区域设置而始终使用点作为小数分隔符,请使用 to-string-unlocalized()。

对于另一个方向,使用 to-float() 成员函数将 string 转换为数字, 并使用 is-float() 检查字符串是否持有有效数字。

所有这些转换都使用当前区域设置的小数分隔符, 它通过 Platform.decimal-separator 暴露,默认为点(.)。 例如,在德语区域设置中,小数分隔符是逗号(,):

  • float 值 1.5 转换为字符串 "1,5"。
  • "1,5".to-float() 返回 1.5。
  • "1.5".is-float() 返回 false,而 "1.5".to-float() 返回 0: 解析时只识别区域设置的小数分隔符。

.slint 文件中的数字字面量始终使用点,无论区域设置如何。 关于小数分隔符如何确定,请参见 翻译指南。


© 2026 SixtyFPS GmbH