如何在QML表单中将焦点从一个控件转移到下一个控件?默认情况下,它可与Tab
按钮一起使用,但我需要将其更改为Enter
。所有控件都按Gridlayout
2列排序。
我已经定义了一个新组件TextFieldMoveOnReturn.qml
import QtQuick 2.0
import QtQuick.Controls 1.1
TextField {
Keys.onReturnPressed: nextItemInFocusChain().forceActiveFocus()
}
如果使用此字段而不是TextField,则将获得所需的行为
edit更好的解决方案:定义一个新组件GridLayoutNextOnReturn.qml
import QtQuick 2.0
import QtQuick.Layouts 1.1
GridLayout {
Keys.onReturnPressed: {
for (var i = 0; i < children.length; ++i)
if (children[i].focus) {
children[i].nextItemInFocusChain().forceActiveFocus()
break
}
}
}
并在其中使用普通的TextField-就像一个魅力一样工作
您可以使用onEditingFinished:
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
Rectangle {
width: 400
height: 400
GridLayout {
anchors.fill: parent
columns: 2
Label {
text: "Name"
}
TextField {
onEditingFinished: addressEdit.focus = true
}
Label {
text: "Address"
}
TextField {
id: addressEdit
}
}
}
使用Keys.onReturnPressed
和forceActiveFocus()
import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.1
Rectangle {
width: 400
height: 400
GridLayout {
anchors.fill: parent
columns: 2
Label {
text: "Name"
}
TextField {
Keys.onReturnPressed: organizationEdit.forceActiveFocus()
}
Label {
text: "Organization"
}
TextField {
id: organizationEdit
Keys.onReturnPressed: addressEdit.forceActiveFocus()
}
Label {
text: "Address"
}
TextField {
id: addressEdit
}
}
}
为了使其更加健壮和灵活,您应该做出相同的行为Tab
和Enter/Return
键。处理keyPressed
事件,并使用KeyNavigation.tab
而不是nextItemInFocusChain
来关注下一个元素,如下所示:
import QtQuick 2.12
import QtQuick.Controls 1.12
Column {
TextField {
id: field1
KeyNavigation.tab: field2
activeFocusOnTab: true
Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
}
TextField {
id: field2
KeyNavigation.tab: field3
activeFocusOnTab: true
Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
}
TextField {
id: field3
KeyNavigation.tab: field1
activeFocusOnTab: true
Keys.onReturnPressed: KeyNavigation.tab.forceActiveFocus();
}
}
因此,您可以控制焦点顺序,并且用户可以交替使用tab
和return
键,从而产生更好的UX。每当您要变更单时,只需更改KeyNavigation.tab
值:)
[注:由于以后的更改和灵活性,我极力建议您避免使用nextItemInFocusChain