Home > OS >  QML give focus to a Component
QML give focus to a Component

Time:05-09

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?

CodePudding user response:

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.

CodePudding user response:

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
    onl oaded: {
        item.forceActiveFocus();
    }
}
  • Related