Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

qt - Android back button press doesn't trigger keys.onreleased qml

I am creating a program in Qt5.3 and Qtquick2.1. I am trying to capture back button press on android in my code using Keys.onReleased. But that event is not getting triggered. Also I have set the item focus to true. But still no success. Here is the code sample

import QtQuick 2.1
import QtQuick.Controls 1.2
import QtQuick.Controls.Styles 1.2
import QtQuick.Layouts 1.1
import QtQuick.Window 2.1

Rectangle
{
    id: main2
    focus: true
    width: Screen.Width
    height: Screen.Height
    Keys.enabled: true
    Keys.priority: Keys.BeforeItem

    property string load_page: ""
    signal deskConnected()

    Loader{
        id: pageloader
        anchors.fill: parent
        source: "qrc:/qml/resources/Firstpage.qml"
    }

    onDeskConnected: {
         pageloader.item.onDeskConnected()
    }

    function loadPatwin(){
        pageloader.source = "qrc:/qml/resources/Secondpage.qml";
    }

    Keys.onReleased: {
        console.log("back");
        if (event.key === Qt.Key_Back) {
            event.accepted=true;
        }
    }
}

Here loadPatwin is the function which gets called on pressing a button which is defined in some other qml. And loads a new qml. But after that when I am pressing the back button on android, the app gets closed and it doesn't print even "back" in the logs. Any suggestions what I am doing wrong here?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In qt quick (Qt5.1 and later) the ApplicationWindow and Window, both have a closing signal that is emitted when the user touches the back button in android. You can simply implement an onClosing handler and set the close parameter to false. Here is how to do it:

onClosing: {
    close.accepted = false
}

By this handler you can easily manage the back button of android device. It does not need any extra permission. For example suppose you have a StackView to manage the GUI. You can write these lines of code, Then your application behaves as like as a native android app:

onClosing: {
        if(stack.depth > 1){
            close.accepted = false
            stack.pop();
        }else{
            return;
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...