The recommendation for handling the back button in various places is to listen for Qt::Key_Back as so: http://qt-project.org/forums/viewthread/29366
I have a StackView based program and the main QML looks like this:
Item {
width: 360
height: 640
focus: true
Keys.onReleased: {
console.log("Key pressed: "+event.key)
if (event.key == Qt.Key_Back) {
console.log("Back button pressed. Stack depth "+stack.depth)
if(stack.depth >= 1) {
event.accepted = true
stack.pop()
}
else
event.accepted = false
}
}
StackView {
id: stack
anchors.fill: parent
}
}
Item {
width: 360
height: 640
focus: true
Keys.onReleased: {
console.log("Key pressed: "+event.key)
if (event.key == Qt.Key_Back) {
console.log("Back button pressed. Stack depth "+stack.depth)
if(stack.depth >= 1) {
event.accepted = true
stack.pop()
}
else
event.accepted = false
}
}
StackView {
id: stack
anchors.fill: parent
}
}
To copy to clipboard, switch view to plain text mode
Most of the time this works. Back button is handled correctly and pops back to the previous screen. But randomly sometimes the back button just kills the app and my Keys.onReleased handler never gets called.
Seems to be unpredictable. Not always on the same screen. Any thoughts on how to implement back button more robustly in Android?
Added after 1 52 minutes:
I worked around this issue by handling the keys in the QQuickView instead.
For those interested.
In the subclass of QQuickView I watch for the back key and emit a custom signal called backPressed with the root object as a parameter:
void QtQuick2ApplicationViewer
::keyPressEvent(QKeyEvent *e
) { if(e->key() != Qt::Key_Back) // pass on everything but the back key
QQuickView::keyPressEvent(e);
}
void QtQuick2ApplicationViewer
::keyReleaseEvent(QKeyEvent *e
) { if(e->key() != Qt::Key_Back) // pass on everything but the back key
QQuickView::keyPressEvent(e);
else
emit backPressed(rootObject());
}
void QtQuick2ApplicationViewer::keyPressEvent(QKeyEvent *e) {
if(e->key() != Qt::Key_Back) // pass on everything but the back key
QQuickView::keyPressEvent(e);
}
void QtQuick2ApplicationViewer::keyReleaseEvent(QKeyEvent *e) {
if(e->key() != Qt::Key_Back) // pass on everything but the back key
QQuickView::keyPressEvent(e);
else
emit backPressed(rootObject());
}
To copy to clipboard, switch view to plain text mode
Then in my main class I handle that signal:
void ShellInterface::onBackPressed(QQuickItem *rootItem) {
QMetaObject::invokeMethod(rootItem,
"handleBackPressed");
}
void ShellInterface::onBackPressed(QQuickItem *rootItem) {
QMetaObject::invokeMethod(rootItem, "handleBackPressed");
}
To copy to clipboard, switch view to plain text mode
then in my main QML Item
function handleBackPressed() {
if(stack.depth >= 1) {
stack.pop()
}
}
function handleBackPressed() {
if(stack.depth >= 1) {
stack.pop()
}
}
To copy to clipboard, switch view to plain text mode
To match android behaviour I should quit the app on the start screen, that would be easy to add.
Bookmarks