Skip to content

某些元素(如 TextInput)接受来自鼠标/手指的输入, 也接受来自(虚拟)键盘的按键事件。为了让一个项目能够接收 这些事件,它必须具有焦点。这可以通过 has-focus(out)属性进行查看。

你可以通过调用 focus() 手动激活某个元素的焦点:

slint
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";        }    }}

同样,你可以通过调用 clear-focus() 手动清除当前已聚焦元素的焦点:

slint
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";        }    }}

清除焦点后,窗口的键盘输入将被丢弃,直到另一个元素被显式 获得焦点为止。例如通过调用 focus()、用户点击某个元素使其获得焦点,或在 按下 Tab 键时定位到第一个可聚焦元素。

如果你已将 TextInput 包装在一个组件中,那么你可以使用 forward-focus 属性 将这种焦点激活转发给应当接收它的元素:

slint
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 {        }    }}

如果在 WindowPopupWindow 上使用 forward-focus 属性,那么所指定的元素将在 窗口首次获得焦点时获得焦点——它会成为初始焦点元素。

基于 MIT 协议发布