简体   繁体   English

QML 将焦点放在一个组件上

[英]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.我试图将焦点放在 rect1 组件中的 Rectangle 上并捕获关键事件,但是使用此代码,焦点始终放在 ItemLoaderPage 上,我无法捕获关键事件。 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.我发现在 Qt 中保持键盘焦点是一个很大的弱点。文档使这一切听起来很简单,但在实践中,我总是会遇到甚至不知道焦点在哪里的情况。

I usually resort to manually calling forceActiveFocus() rather than depending on Qt to do the right thing automatically.我通常求助于手动调用 forceActiveFocus() 而不是依赖 Qt 来自动执行正确的操作。 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: Loader 和矩形已通过您的属性请求焦点:

focus: true

You should try to set the focus only once if I get the idea of the focus-attribute right.如果我对 focus-attribute 的理解正确,你应该尝试只设置一次焦点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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