我有一个桌面的QtQuick项目。这很简单:
// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
Rectangle {
width: 360
height: 360
Grid
{
id: xGrid
width: parent.width
height: parent.height
columns: 2
spacing: 1
Rectangle
{
height: parent.height
width: 10
color: "#ff0000"
Text {
id: xText
text: qsTr("t\na\ns")
}
}
TextEdit
{
id: xTextEdit
height: parent.height
width: 350
Keys.onEnterPressed: {
console.log(event.key)
xText.text = (qsTr("A"))
}
}
}
}
我的代码没有像我想的那样运行。 Keys.onEnterPressed
似乎永远不会被捕获,所以我尝试Keys.onPressed
它工作,但不知道为什么当我按Enter键时,even.key
返回16777220。
有谁得到这个问题?我该如何解决? 感谢您的回答!
我用TextInput
项目遇到了同样的问题。我试过了
onPressed
onEnterPressed
onReturnPressed
只有后者才有效(onReturnPressed
)。我想,TextInput
的底层实现捕获了'Enter'键,因此它不会被常规方式的onPressed
信号处理。
顺便说一下:关键代码是正确的。它是平台特定密钥代码的抽象。
TextArea {
id: messageField
Layout.fillWidth: true
placeholderText: qsTr("Message")
wrapMode: TextArea.Wrap
inputMethodHints: Qt.ImhNoPredictiveText
function _onEnterPressed(event)
{
if ((event.modifiers & Qt.ControlModifier))
{
sendMessage()
}
else
{
event.accepted = false;
}
}
Keys.onReturnPressed: { _onEnterPressed(event) }
Keys.onEnterPressed: { _onEnterPressed(event) }
}
处理输入文本值的用户的更好方法是使用TextInput.onAccepted
这是一个例子:
TextInput {
onAccepted: processText()
}
当用户按Enter键时,将调用processText()方法。这种方法更简单,可以提高跨平台的可移植性。
我也说使用onReturnPressed。否则你也可以检查onPressed()中的键值并做出反应。 onReturn / EnterPressed只是便利功能。
从docs获得的潜在相关背景:
[...]关键事件处理的顺序是:
- 在forwardTo中指定的项目
- 特定的密钥处理程序,例如onReturnPressed
- onPressed,onReleased处理程序
- 项目特定的密钥处理,例如TextInput键处理
- 父项目