请求焦点的多个子项目如何在FocusScope类型中获得焦点?



我是QML的新手,我对FocusScope类型感到困惑。我的理解是,当多个项目请求焦点时,它用于控制应用程序部分的焦点。

文档说:

概念上聚焦范围是相当简单的。

在每个焦点范围内,一个元素可以将Item::focus设置为true。如果多个Item设置了focus属性,则最后一个元素设置了焦点就会有焦点而其他的都不设置,类似当没有聚焦范围时。

那么,当程序运行时,为什么下面代码中的第一个文本字段集中而不是最后一个?

import QtQuick 2.0
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.15
ApplicationWindow{
visible: true
width: 200
height: 200
FocusScope{
Column{
Text{text: "first focus scope"}
TextField {
width: 100; height: 25; focus: true
text: focus
}
TextField{
width: 100; height: 25; focus: true
text: focus
}
Text{text: "second focus scope"}
TextField {
width: 100; height: 25; focus: true
text: focus
}
TextField{
width: 100; height: 25; focus: true
text: focus
}
}
}
}

任何帮助都非常感谢!

属性设置顺序未定义:

作为一般规则,用户不应该依赖于绑定的求值顺序。

你可以通过下面的代码看到它们实际设置的顺序:

import QtQuick 2.0
import QtQuick.Controls 2.14
import QtQuick.Layouts 1.15
ApplicationWindow {
width: 200
height: 200
visible: true
FocusScope {
Column {
Text {
text: "first focus scope"
}
TextField {
objectName: "textField1"
width: 100
height: 25
text: focus
focus: {
print(objectName, "setting focus to true")
true
}
onFocusChanged: print(objectName, "focus changed to", focus)
}
TextField {
objectName: "textField2"
width: 100
height: 25
text: focus
focus: {
print(objectName, "setting focus to true")
true
}
onFocusChanged: print(objectName, "focus changed to", focus)
}
Text {
text: "second focus scope"
}
TextField {
objectName: "textField3"
width: 100
height: 25
text: focus
focus: {
print(objectName, "setting focus to true")
true
}
onFocusChanged: print(objectName, "focus changed to", focus)
}
TextField {
objectName: "textField4"
width: 100
height: 25
text: focus
focus: {
print(objectName, "setting focus to true")
true
}
onFocusChanged: print(objectName, "focus changed to", focus)
}
}
}
}

输出:

qml: textField4 setting focus to true
qml: textField4 focus changed to true
qml: textField3 setting focus to true
qml: textField4 focus changed to false
qml: textField3 focus changed to true
qml: textField2 setting focus to true
qml: textField3 focus changed to false
qml: textField2 focus changed to true
qml: textField1 setting focus to true
qml: textField2 focus changed to false
qml: textField1 focus changed to true

一次只能有一个活动焦点项,因此将多个兄弟项的焦点设置为true没有多大意义。

如果你想让第一个TextField专注于启动,我就这样做:

ApplicationWindow {
// ...
Component.onCompleted: textField1.forceActiveFocus()

相关内容

最新更新