首页 > 解决方案 > 如何使用 TAB 和 SHIFT+TAB 在 macOS 中的自定义 QML 控件上循环 activeFocus?

问题描述

我在使用键盘上的 TAB 和 SHIFT+TAB 来循环我的自定义控件上的activeFocus时遇到问题。当我有一组自定义控件时,TAB 键总是传递给父小部件,而不是更改我的自定义控件上的activeFocus 。但是,当我使用TextField时,焦点会在控件中循环,正如预期的那样。

这是一个基于https://www.219design.com/a-tale-of-efficient-keyboard-navigation-code-in-qml/的示例:

主窗口.qml

import QtQuick 2.12
import QtQuick.Controls 2.12

Rectangle {
  color: "white"
  width: 240
  height: 240

  Label {
    id: heading
    width: parent.width
    wrapMode: Text.Wrap
    padding: 10
    text: 'Use TAB and SHIFT+TAB to move focus'
  }

  Column {
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.top: heading.bottom
    spacing: 15

    Widget {
      color: "yellow"
      focus: true
    }
    Widget {
      color: "orange"
    }
    Widget {
      color: "green"
    }
    Widget {
      color: "red"
    }
  }
}

Widget.qml - 这不起作用

import QtQuick 2.12
import QtQuick.Controls 2.12

Pane {
  id: root
  property color color

  width: 175
  height: 25

  focusPolicy: Qt.StrongFocus
  activeFocusOnTab: true

  background: Rectangle {
    color: root.color
    radius: 10
    antialiasing: true
  }

  Label {
    id: label
    anchors.fill: parent
    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
    text: root.activeFocus ? 'I have focus' : ''
  }
}

Widget.qml - 这行得通

import QtQuick 2.12
import QtQuick.Controls 2.12

TextField {
  id: root
  property color color

  width: 175
  height: 25

  background: Rectangle {
    color: root.color
    radius: 10
    antialiasing: true
  }

  Label {
    id: label
    anchors.fill: parent
    horizontalAlignment: Text.AlignHCenter
    verticalAlignment: Text.AlignVCenter
    text: root.activeFocus ? 'I have focus' : ''
  }
}

我究竟做错了什么?如何使用 TAB 和 SHIFT+TAB 在自定义控件上循环activeFocus ?


更新:我刚刚发现这只发生在 macOS 上。上面的例子都可以在 Windows 上正常工作。

标签: qtqmlqtquickcontrols2

解决方案


这最终是由 Mac 系统设置引起的。在 macOS Catalina (10.15.5) 上,打开系统偏好设置 -> 键盘 -> 快捷方式。选中“使用键盘导航在控件之间移动焦点”。(感谢https://stackoverflow.com/a/55062814/195123


推荐阅读