forceActiveFocus() 与 QML 中的 focus = true

forceActiveFocus() vs focus = true in QML

我阅读了有关以下内容的文档:

但仍然不清楚什么时候应该有人使用 forceActiveFocus() 方法将 focus 属性 设置为 true,反之亦然。

作为 documentation states:

For very simple cases simply setting the focus property is sometimes sufficient.

如果得到 focus: trueItem 没有被可能没有焦点的 FocusScope 包围,那么这种简单的情况就是。

然后继续:

> Within each focus scope one object may have Item::focus set to true. If more than one Item has the focus property set, the last type to set the focus will have the focus and the others are unset, similar to when there are no focus scopes.

> When a focus scope receives active focus, the contained type with focus set (if any) also gets the active focus. If this type is also a FocusScope, the proxying behavior continues. Both the focus scope and the sub-focused item will have the activeFocus property set.

据我们了解,设置 focus: true 是不够的,如果 ItemFocusScope 的后继者 [=13] =] 需要 activeFocus su 继任者 Item 将获得 activeFocus。这是递归的,意味着 FocusScope 需要 focus: true 并且可能的前任 FocusScope 需要 activeFocus 等等。这导致某种焦点树

这个焦点树内部节点组成,即FocusScope叶子ItemFocusScope 也可能是 叶子 ,但我不知道为什么会这样。

在这棵树中,每个FocusScope最多可以有一个child节点Item) or FocusScope (inner node) that has focus === true. 遍历这棵树,沿着所有遍历的节点都有[=31=的路径]遍历的节点也有activeFocus === true。因为每个FocusScope可能最多只有一个child节点focus === true所以只有一条这样的路。

Column {
    FocusScope {
        focus: false
        width: 100
        height: 100
        Text {
            focus: true
            text: 'has focus ' + focus + '\nhas activeFocus ' + activeFocus
        }
    }
    FocusScope {
        focus: true
        width: 100
        height: 100
        Text {
            focus: true
            text: 'has focus ' + focus + '\nhas activeFocus ' + activeFocus
        }
    }
}

这里有两个 FocusScope。两者都有一个 child 有 focus,但因为只有第二个 FocusScopefocus 本身,它的 child 有 activeFocus.

利用forceActiveFocus()遍历焦点树,途中对每个节点设置focustrue,所以ItemactiveFocus 最后。