Qt 无法在StackView项目内的TextEdit中检索焦点

Qt 无法在StackView项目内的TextEdit中检索焦点,qt,qml,Qt,Qml,我不明白它为什么不能正常工作。当窗口弹出时,我想将TextEdit focus设置为true。TextEdit只能在单击其区域后才能接收关键事件 main.qml ApplicationWindow { id:aplWin visible: true minimumWidth: 1280 minimumHeight: 1024 StackView { id: stackView anchors.fill: parent

我不明白它为什么不能正常工作。当窗口弹出时,我想将TextEdit focus设置为true。TextEdit只能在单击其区域后才能接收关键事件

main.qml

ApplicationWindow {
    id:aplWin
    visible: true
    minimumWidth:  1280
    minimumHeight: 1024

    StackView {
        id: stackView
        anchors.fill: parent
        initialItem: SignInWin {}
    }
}
Page {
    id: root
    width: parent.width + 500
    height: parent.height

    Rectangle {
        border.color: "black"
        y: 200
        width: 50
        height: 20
        z: 1
        TextEdit {
            anchors.fill: parent
            color: "black"
            focus: true
        }
    }
}
SignInWin.qml

ApplicationWindow {
    id:aplWin
    visible: true
    minimumWidth:  1280
    minimumHeight: 1024

    StackView {
        id: stackView
        anchors.fill: parent
        initialItem: SignInWin {}
    }
}
Page {
    id: root
    width: parent.width + 500
    height: parent.height

    Rectangle {
        border.color: "black"
        y: 200
        width: 50
        height: 20
        z: 1
        TextEdit {
            anchors.fill: parent
            color: "black"
            focus: true
        }
    }
}

问题在于:

焦点树中有多个层。每个
FocusScope
都可以有一个子系统具有焦点。现在你有了:

StackView -> Page -> TextEdit
让我困惑的是,
页面
的行为就像是一个
聚焦镜
,但并不是这样记录的

这意味着,除非
页面
堆栈视图
具有,否则
文本编辑
将不会具有
activeFocus
。但是需要
activeFocus
来检索输入

因此,您可以使用方法
forceActiveFocus()
,该方法将迭代焦点层次结构,并为每个
FocusScope
请求焦点,或者为层次结构中的每个层将
focus
-属性设置为
true

ApplicationWindow {
    id:aplWin
    visible: true
    minimumWidth:  1280
    minimumHeight: 1024

    StackView {
        id: stackView
        anchors.fill: parent
        initialItem: SignInWin {}
        focus: true // <--- HERE!
    }
}

Page {
    id: root
    width: parent.width + 500
    height: parent.height
    focus: true // <--- AND HERE

    Rectangle {
        border.color: "black"
        y: 200
        width: 50
        height: 20
        z: 1
        TextEdit {
            anchors.fill: parent
            color: "black"
            focus: true
        }
    }
}
ApplicationWindow{
id:aplWin
可见:正确
最小宽度:1280
最小高度:1024
斯塔克维尤{
id:stackView
锚定。填充:父级
initialItem:SignInWin{}
焦点:true//当
Component.onComplete时尝试
forceActiveFocus()