简体   繁体   中英

QML give focus to a Component

I have this code:

//main.qml
Window {
    id: root
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
    objectName: "Window"

    onActiveFocusItemChanged: console.log("***** ACTIVE FOCUS:", activeFocusItem, "*****")

    StackView {
        anchors.fill: parent
        initialItem: "qrc:/LoaderPage.qml"
        objectName: "StackView"
        onCurrentItemChanged: currentItem.forceActiveFocus()
    }
}


//LoaderPage.qml
Item {
    objectName: "ItemLoaderPage"
//    Keys.forwardTo: loader

    Loader {
        id: loader
        anchors.fill: parent
        objectName: "Loader"
        focus: true
        sourceComponent: rect1
    }

    Component {
        id: rect1

        Rectangle {
            Keys.onReleased: {
                if(event.key === Qt.Key_Escape || event.key === Qt.Key_Back)
                {
                    console.log("Esc or back pressed from", objectName)
                    event.accepted = true
                }
            }

            objectName: "Rectangle"
            focus: true
            color: "blue"
        }
    }
}

I am trying to give the focus to the Rectangle in rect1 Component and catch key events, but with this code, the focus is always given to ItemLoaderPage and I am not able to catch key events. How can I solve that?

I find that maintaining keyboard focus is a big weakness in Qt. The docs make it all sound so straightforward, but in practice I am always ending up in situations where I can't even tell where the focus went.

I usually resort to manually calling forceActiveFocus() rather than depending on Qt to do the right thing automatically. It's a fragile solution, but it's at least one that I feel I have control over.

Loader {
    sourceComponent: rect1
    onLoaded: {
        item.forceActiveFocus();
    }
}

The Loader and the rectangle has requested the focus by your attribute:

focus: true

You should try to set the focus only once if I get the idea of the focus-attribute right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM