Item的屬性:
read-only activeFocus : bool
This property indicates whether the item has active focus.
An item with active focus will receive keyboard input, or is a FocusScope ancestor of the item that will receive keyboard input.
Usually, activeFocus is gained by setting focus on an item and its enclosing FocusScopes.(兩個都要focus) In the following example input will have activeFocus.
Rectangle {
FocusScope {
focus: true
TextInput {
id: input
focus: true
}
}
}
focus : bool
This property indicates whether the item has focus within the enclosing focus scope. If true, this item will gain active focus when the enclosing focus scope gains active focus. (當包圍的focus scope得到active focus時候, 它也會得到 active focus)In the following example, input will be given active focus when scope gains active focus.
Rectangle {
FocusScope {
id: scope
TextInput {
id: input
focus: true
}
}
}
For the purposes of this property, the scene as a whole is assumed to act like a focus scope. On a practical level, that means the following QML will give active focus to input on startup.
Rectangle {
TextInput {
id: input
focus: true
}
}
See also activeFocus and Keyboard Focus.
Keyboard Focus in QML
This problem is fundamentally one of visibility。這個問題是由於可見度引起的。
/////////////////////////////////////////////////////////////////////////////////////
例子:
import Qt 4.7
//example from:
//http://developer.qt.nokia.com/doc/qt-4.7/qml-focusscope.html
/*
Blue border indicates scoped focus
Black border indicates NOT scoped focus
Red box indicates active focus
Use arrow keys to navigate
*/
Rectangle {
color: "white"
width: 480
height: 480
FocusScope {
id: myScope
focus: true
Rectangle {
height: 120
width: 420
color: "transparent"
border.width: 5
border.color: myScope.activeFocus?"blue":"black"
Rectangle {
id: item1
x: 10; y: 10
width: 100; height: 100; color: "green"
border.width: 5
border.color: activeFocus?"blue":"black"
KeyNavigation.right: item2
focus: true
Rectangle {
width: 50; height: 50; anchors.centerIn: parent
color: parent.focus?"red":"transparent"
}
}
Rectangle {
id: item2
x: 310; y: 10
width: 100; height: 100; color: "green"
border.width: 5
border.color: activeFocus?"blue":"black"
KeyNavigation.left: item1
Keys.onDigit9Pressed: console.log("Top Right");
Rectangle {
width: 50; height: 50; anchors.centerIn: parent
color: parent.focus?"red":"transparent"
}
}
}
KeyNavigation.down: item3
}
Rectangle {
id: item3
x: 10; y: 300
width: 100; height: 100; color: "green"
border.width: 5
border.color: activeFocus?"blue":"black"
KeyNavigation.up: myScope
Rectangle {
width: 50; height: 50; anchors.centerIn: parent
color: parent.focus?"red":"transparent"
}
}
}
//總結:activeFocus 才是真正的焦點
//focus只是說明當前component的哪個將要擷取焦點
activeFocus是read-only的,所以要設定焦點要用focus。
http://developer.qt.nokia.com/forums/viewthread/3261