Knute Knudsen
Knute Knudsen

Reputation: 1239

How to cycle activeFocus on custom QML controls in macOS using TAB and SHIFT+TAB?

I'm having trouble using TAB & SHIFT+TAB on the keyboard to cycle activeFocus on my custom controls. When I have a group of custom controls, the TAB key is always passed up to the parent widget instead of changing activeFocus on my custom controls. However, when I use, say, a TextField the focus is cycled through the controls, as expected.

Here is an example, based on https://www.219design.com/a-tale-of-efficient-keyboard-navigation-code-in-qml/:

MainWindow.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 - this doesn't work

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 - this works

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' : ''
  }
}

What am I doing wrong? How can I cycle activeFocus on my custom controls using TAB and SHIFT+TAB?


UPDATE: I just discovered that this only occurs on macOS. The above examples both work fine on Windows.

Upvotes: 1

Views: 241

Answers (1)

Knute Knudsen
Knute Knudsen

Reputation: 1239

This ended up being caused by a Mac system setting. On macOS Catalina (10.15.5), open System Preferences -> Keyboard -> Shortcuts. Check "Use keyboard navigation to move focus between controls". (Thanks to https://stackoverflow.com/a/55062814/195123)

Upvotes: 1

Related Questions