焦点处理
某些元素(如 TextInput)既接受来自鼠标/手指的输入,也接受来自(虚拟)键盘的按键事件。
为了让某个项能够接收这些事件,它必须拥有焦点。这可以通过 has-focus(out)属性观察到。
你可以通过调用 focus() 手动将焦点激活到某个元素上:
import { Button } from "std-widgets.slint";
export component App inherits Window { VerticalLayout { alignment: start; Button { text: "press me"; clicked => { input.focus(); } } input := TextInput { text: "I am a text input field"; } }}slint
同样,你可以通过调用 clear-focus() 手动清除当前聚焦元素的焦点:
import { Button } from "std-widgets.slint";
export component App inherits Window { VerticalLayout { alignment: start; Button { text: "press me"; clicked => { input.clear-focus(); } } input := TextInput { text: "I am a text input field"; } }}slint
清除焦点后,发送到窗口的键盘输入会被丢弃,直到另一个元素被显式聚焦。
例如,通过调用 focus()、用户点击某个元素使其获得焦点,或者
按下 tab 键并找到第一个可聚焦元素时。
如果你将 TextInput 包装在一个组件中,那么你可以使用 forward-focus 属性
转发这种焦点激活,指向应该接收焦点的元素:
import { Button } from "std-widgets.slint";
component LabeledInput inherits GridLayout { forward-focus: input; Row { Text { text: "Input Label:"; } input := TextInput {} }}
export component App inherits Window { GridLayout { Button { text: "press me"; clicked => { label.focus(); } } label := LabeledInput { } }}slint
如果你在 Window 或 PopupWindow 上使用 forward-focus 属性,那么指定的元素将在
窗口第一次获得焦点时接收焦点——它成为初始焦点元素。
© 2026 SixtyFPS GmbH