QML提供了对应的按键处理方法,我们接下来实现一个通过键盘上的方向键来移动文本,代码如下:
1 import QtQuick 2.4 2 import QtQuick.Controls 1.3 3 import QtQuick.Window 2.2 4 import QtQuick.Dialogs 1.2 5 6 Rectangle{ 7 id: root 8 512 9 height: 512 10 color: "gray" 11 12 focus: true 13 Keys.enabled: true 14 Keys.onEscapePressed: Qt.quit(); 15 Keys.forwardTo: [moveText, likeQt]; 16 17 Text { 18 id: moveText 19 x: 20; y: 20; 20 200; height: 30; 21 22 text: "Moving Text" 23 color: "blue" 24 font {bold: true; pixelSize: 30} 25 26 Keys.enabled: true 27 Keys.onPressed: { 28 switch (event.key){ 29 case Qt.Key_Left: 30 x -= 10; 31 break; 32 case Qt.Key_Right: 33 x += 10; 34 break; 35 case Qt.Key_Up: 36 y -= 10; 37 break; 38 case Qt.Key_Down: 39 y += 10; 40 break; 41 default: 42 return; 43 } 44 event.accepted = true; 45 } 46 } 47 48 CheckBox { 49 id: likeQt 50 text: "Like Qt Quick" 51 z:1 52 53 anchors.left: parent.left 54 anchors.leftMargin: 10 55 anchors.bottom: parent.bottom 56 anchors.bottomMargin: 10 57 } 58 }