焦點是QtQuick中的一個鏈。 這意味着所有的祖先FocusScope下載到當前活動的孩子獲得積極的焦點。
FocusScope用於製作更簡單的焦點抽象:告訴自定義組件,當根對象獲得活動焦點時,必須將其轉發給給定的子項。
在下面的例子:
import QtQuick 2.0;
Rectangle {
width: 400;
height: 200;
focus: true;
FocusScope {
id: scope1;
anchors {
top: parent.top;
left: parent.left;
right: parent.right;
bottom: parent.verticalCenter;
}
Rectangle {
id: rect1;
color: (scope1.activeFocus ? "yellow" : "gray");
border.width: 1;
anchors.fill: parent;
MouseArea {
anchors.fill: parent;
onClicked: { scope1.forceActiveFocus(); }
}
TextInput {
id: input1;
focus: true;
anchors.centerIn: parent;
}
}
}
FocusScope {
id: scope2;
anchors {
top: parent.verticalCenter;
left: parent.left;
right: parent.right;
bottom: parent.bottom;
}
Rectangle {
id: rect2;
color: (scope2.activeFocus ? "yellow" : "gray");
border.width: 1;
anchors.fill: parent;
MouseArea {
anchors.fill: parent;
onClicked: { scope2.forceActiveFocus(); }
}
TextInput {
id: input2;
focus: true;
anchors.centerIn: parent;
}
}
}
}
...我們想要兩個,可以有重點,我們不necessarly想明確地專注於內部的TextInput(因爲他們理想的將是一個自定義的內部大區組件,因此不能從外部訪問)。
所以當一個區域被點擊時,我們將主動焦點賦予父範圍,並且範圍會自動將其指向具有焦點的子節點:true標誌(表示它需要焦點,而不是它具有它,這就是爲什麼我們在每個TextInput中都有一個標誌)。
需要知道內部輸入是否具有活動焦點的項目將僅僅請求範圍是否具有活動焦點。他們不必關心是在裏面。
如果範圍包含具有焦點的另一個範圍:true,則焦點會再次轉發,直到達到需要焦點的最新項目。
我當然可以編寫自己的遞歸檢查hasFocus()函數。但也許有更好的辦法... – HWende