unable to detect key press in StackView
-
wrote on 15 Feb 2016, 13:32 last edited by m_andrej
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?
-
wrote on 15 Feb 2016, 15:34 last edited by
Hi,
keyboard event handling depends on the focussed element. If you want to press Return anywhere in your StackView, your second approach is the right one. -
wrote on 15 Feb 2016, 15:42 last edited by
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.
-
wrote on 16 Feb 2016, 10:23 last edited by
You should succeed with forceActiveFocus() on the currentItem:
onCurrentItemChanged: { if (currentItem) { currentItem.forceActiveFocus() } }
-
wrote on 16 Feb 2016, 14:11 last edited by
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") } } }
1/5