Qt 检查子体在QML中是否具有activeFocus==true
在深度嵌套的QML GUI中,是否有一种简单的方法可以确定项目的任何子项或孙子项等是否具有activeFocus==trueQt 检查子体在QML中是否具有activeFocus==true,qt,qml,qt5,qqmlcomponent,Qt,Qml,Qt5,Qqmlcomponent,在深度嵌套的QML GUI中,是否有一种简单的方法可以确定项目的任何子项或孙子项等是否具有activeFocus==true 不必从基本祖先向下钻取层次结构,您可以从当前祖先向上钻取: 遍历所有子对象并检查activeFocus?对n个孩子来说,这还不够容易吗?此外,还必须按照建议的策略递归地进行。我希望在QML中有一种内置的方式。我不认为在QML项目中实现如此昂贵且很少使用的功能是正确的。是的,你必须递归地遍历所有的子对象。但我会以声明的方式这样做,也就是说,我会从children通知pare
不必从基本祖先向下钻取层次结构,您可以从当前祖先向上钻取:
遍历所有子对象并检查activeFocus?对n个孩子来说,这还不够容易吗?此外,还必须按照建议的策略递归地进行。我希望在QML中有一种内置的方式。我不认为在QML项目中实现如此昂贵且很少使用的功能是正确的。是的,你必须递归地遍历所有的子对象。但我会以声明的方式这样做,也就是说,我会从children通知parent更改属性,例如,在children:onActiveFocusChanged:{ifactiveFocus parent.focusCounter-;else parent.focusCounter++;}
Item {
id: intermediateItem
visible: anyDescendantHasActiveFocus(intermediateItem) ? true : false
Item {
Item {
Item {
id: hasActiveFocus
Component.onCompleted: hasActiveFocus.forceActiveFocus()
}
}
}
}
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
ApplicationWindow {
id: window
visible: true
width: 640
height: 480
function anyDescendantHasActiveFocus(ancestor) {
let item = ancestor.Window.activeFocusItem;
while (item) {
if (item === ancestor)
return true;
item = item.parent;
}
return false;
}
Row {
anchors.centerIn: parent
spacing: 10
Repeater {
model: 3
Rectangle {
width: 200
height: 100
border.width: 1
border.color: anyDescendantHasActiveFocus(this) ? "red" : "black"
Rectangle {
anchors.fill: parent; anchors.margins: 10
border.width: 1
Rectangle {
anchors.fill: parent; anchors.margins: 10
border.width: 1
Rectangle {
anchors.fill: parent; anchors.margins: 10
border.width: 1
Button {
anchors.centerIn: parent
text: "Focus me"
}
}
}
}
}
}
}
}