【发布时间】:2018-01-29 06:31:46
【问题描述】:
这是我的 QML 文件中的代码:
main.qml
Rectangle {
id: window
color: "white"; width: 240; height: 150
Column {
anchors.centerIn: parent; spacing: 15
MyClickableWidget {
focus: true //set this MyWidget to receive the focus
color: "lightblue"
}
MyClickableWidget {
color: "palegreen"
}
}
}
MyClickableWidget.qml
FocusScope {
id: scope
//i try to set true instead of the mouse event
//focus: true
//FocusScope needs to bind to visual properties of the children
property alias color: rectangle.color
x: rectangle.x; y: rectangle.y
width: rectangle.width; height: rectangle.height
Rectangle {
id: rectangle
anchors.centerIn: parent
color: "lightsteelblue"; width: 175; height: 25; radius: 10; antialiasing: true
Text { id: label; anchors.centerIn: parent }
focus: true
Keys.onPressed: {
if (event.key == Qt.Key_A)
label.text = 'Key A was pressed'
else if (event.key == Qt.Key_B)
label.text = 'Key B was pressed'
else if (event.key == Qt.Key_C)
label.text = 'Key C was pressed'
}
}
MouseArea { anchors.fill: parent; onClicked: { scope.focus = true } }
}
我对这段代码有两个问题:
First.第一个组件已设置为focus: true。然后当按下键时,它将显示文本。但我不清楚为什么单击MyClickableWidget 会使其获得焦点,而另一个小部件会失去焦点?点击事件是否将焦点赋予组件?如果是,哪个部分会获得焦点(scope 或rectangle)?
另外,在我看来,如下所示的行是将scope.focus 设置为true。所以,我注释掉这一行,在scope 中插入一行focus = true。但是它不起作用,不能将关键焦点传递给其他项目。为什么?
// MouseArea { anchors.fill: parent; onClicked: { scope.focus = true } }
结果是一样的。我不知道为什么代码需要这一行。
第二个。在焦点范围内,如果子级有focus: true,所有的父级和根级都会自动设置focus: true?如果不在焦点范围内,结果是否相同?
【问题讨论】: