unable to detect key press in StackView
-
Keyboard event handling totally doesn't work as described in the docs: http://doc.qt.io/qt-5/qml-qtquick-keys.html
This program does nothing when Return is pressed:
import QtQuick 2.5 import QtQuick.Controls 1.4 import QtQuick.Window 2.2 Window { visible: true StackView { anchors.fill: parent initialItem: Rectangle { color: "lightblue" focus: true Keys.onReturnPressed: console.log("return") } } }
However, it does work when I move the key handling code out of initialItem:
Window { visible: true StackView { anchors.fill: parent initialItem: Rectangle { color: "lightblue" } focus: true Keys.onReturnPressed: console.log("return") } }
Any ideas why?
-
OK, so why isn't the light blue Rectangle focused when I set its focus property to true?
The second approach isn't useful because I need to process key events inside the items which are pushed to StackView. The key handling depends on the currently pushed item.
-
One handy way to investigate focus issues is to output Window::activeFocusItem to see where the focus is.
Window { onActiveFocusItemChanged: console.log(activeFocusItem) }
You'll notice that it outputs "qml: QQuickRootItem(0x15af1d48)", that is, the root item of the window. StackView is a focus scope, so it seems to help to say "focus: true" for both, the StackView and the Rectangle. When StackView itself has focus, the focus will be automatically transferred to the initial item.
import QtQuick 2.5 import QtQuick.Controls 1.4 import QtQuick.Window 2.2 Window { visible: true StackView { focus: true anchors.fill: parent initialItem: Rectangle { color: "lightblue" focus: true Keys.onReturnPressed: console.log("return") } } }