本页内容

KeyNavigation QML Type (Uncreatable)

支持使用方向键进行键控导航。更多...

Import Statement: import QtQuick

注意:这是一个不可创建的类型。无法在 QML 中对其进行实例化。

附加属性

详细说明

基于键盘的用户界面通常允许使用方向键在可获得焦点的项目之间进行导航。KeyNavigation 附加类型通过提供一种便捷的方式来指定在按下方向键或 Tab 键时应获得焦点的项目,从而实现了此行为。

以下示例为一个 2x2 的项目网格提供了键导航功能:

import QtQuick

Grid {
    width: 100; height: 100
    columns: 2

    Rectangle {
        id: topLeft
        width: 50; height: 50
        color: focus ? "red" : "lightgray"
        focus: true

        KeyNavigation.right: topRight
        KeyNavigation.down: bottomLeft
    }

    Rectangle {
        id: topRight
        width: 50; height: 50
        color: focus ? "red" : "lightgray"

        KeyNavigation.left: topLeft
        KeyNavigation.down: bottomRight
    }

    Rectangle {
        id: bottomLeft
        width: 50; height: 50
        color: focus ? "red" : "lightgray"

        KeyNavigation.right: bottomRight
        KeyNavigation.up: topLeft
    }

    Rectangle {
        id: bottomRight
        width: 50; height: 50
        color: focus ? "red" : "lightgray"

        KeyNavigation.left: bottomLeft
        KeyNavigation.up: topRight
    }
}

通过将focus 设置为true ,左上角的项目最初会获得焦点。当按下箭头键时,焦点将移动到相应的项目,具体由为 KeyNavigation 的left 、right 、up 或down 属性所设定的值决定。

请注意,如果 KeyNavigation 的附加类型接收到了请求的箭头键或 Tab 键的按下和释放事件,则该事件会被接受,且不会进一步传播。

默认情况下,KeyNavigation会在其所附加的项目之后接收键盘事件。如果该项目接受了该键盘事件,则 KeyNavigation 附加类型将不会收到该键的事件。将priority 属性设置为KeyNavigation.BeforeItem ,可使该事件用于项目之前的键盘导航,而非之后。

如果焦点切换到的项目未启用或不可见,系统将尝试跳过该项目并聚焦于下一个项目。当存在一串具有相同 KeyNavigation 处理程序的项目时,此操作是可行的。如果连续多个项目未启用或不可见,它们也将被跳过。

KeyNavigation 会隐式地设置反向操作,以便将焦点返回到该项上。因此,如果您将 `left ` 设置为另一个项,该项的 KeyNavigation 中的 `right ` 就会被设置,以将焦点设回该项。 但是,如果该项的 KeyNavigation 已显式设置了向右方向,则不会发生任何变化。这意味着上例中,即使未为任何项指定 KeyNavigation.right 或 KeyNavigation.down,也能实现相同的行为。

另请参阅 Keys attached property 。

附加属性文档

KeyNavigation.backtab : Item [attached]

该属性用于存储在按下 Shift+Tab 组合键(Backtab)时应将焦点分配到的控件。

KeyNavigation.down : Item [attached]

该属性用于存储按下向下光标键时应将焦点赋予的控件。

KeyNavigation.left : Item [attached]

该属性用于存储按下左方向键时应将焦点分配到的项目。

KeyNavigation.priority : enumeration [attached]

此属性用于确定在处理附加项自身的键处理之前还是之后处理这些键。

常量描述
KeyNavigation.BeforeItem在常规项目键处理之前处理键事件。如果该事件用于键导航,则会被接受,且不会传递给该项目。
KeyNavigation.AfterItem(默认) 在常规项目键处理之后处理键事件。如果项目接受该键事件,则该事件不会由KeyNavigation 附加属性处理程序进行处理。

KeyNavigation.right : Item [attached]

该属性用于存储按下右方向键时应将焦点分配到的项目。

KeyNavigation.tab : Item [attached]

该属性用于存储按下 Tab 键时应将焦点分配到的控件。

KeyNavigation.up : Item [attached]

该属性用于存储在按下向上光标键时应将焦点赋予的控件。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.