使用例 - QMLでユーザー入力に応答する
サポートされているユーザー入力の種類
QMLの Qt Quickモジュールは、マウスやタッチイベント、テキスト入力、キー押下イベントなど、最も一般的なタイプのユーザ入力をサポートしています。他のモジュールでは、他のタイプのユーザ入力をサポートしています。
この記事では、基本的なユーザー入力の処理方法について説明します。オーディオビジュアル入力については Qt Multimediaドキュメントを参照してください。
マウスイベントとタッチイベント
入力ハンドラによって、QMLアプリケーションはマウスやタッチのイベントを扱うことができます。例えば、イメージにTapHandler を追加したり、Rectangle にText オブジェクトを追加することで、ボタンを作成することができます。TapHandler はあらゆるタイプのポインティングデバイスのタップやクリックに反応します。
import QtQuick Item { id: root width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Rectangle { id: rectangle x: 40 y: 20 width: 120 height: 120 color: "red" TapHandler { onTapped: rectangle.width += 10 } } }
注意: いくつかのItemタイプは、独自の入力処理を内蔵しています。例えば、Flickable はマウスドラッグ、タッチフリック、マウスホイールスクロールに反応します。
キーボードとボタンのイベント
デバイス上のボタン、キーパッド、キーボードからのボタンやキーの押下は、すべてKeys のアタッチド・プロパティを使って処理することができます。このattachedプロパティは、すべてのItem 派生タイプで利用可能で、Item::focus プロパティと連携して、どのタイプがキーイベントを受け取るかを決定します。単純なキー処理であれば、Item のフォーカスを true に設定し、そこですべてのキー処理を行うことができます。
import QtQuick Item { id: root width: 320 height: 480 Rectangle { color: "#272822" width: 320 height: 480 } Rectangle { id: rectangle x: 40 y: 20 width: 120 height: 120 color: "red" focus: true Keys.onUpPressed: rectangle.y -= 10 Keys.onDownPressed: rectangle.y += 10 Keys.onLeftPressed: rectangle.x += 10 Keys.onRightPressed: rectangle.x -= 10 } }
テキスト入力については、いくつかのQMLタイプから選択することができます。TextInput はスタイルのない1行の編集可能なテキストを提供しますが、TextField はアプリケーションのフォームフィールドにより適しています。TextEdit は複数行の編集可能なテキストを扱うことができますが、TextArea はスタイルが追加されるので、より良い選択肢です。
以下のスニペットは、アプリケーションでこれらの型を使用する方法を示しています:
import QtQuick import QtQuick.Controls import QtQuick.Layouts ApplicationWindow { width: 300 height: 200 visible: true ColumnLayout { anchors.fill: parent TextField { id: singleline text: "Initial Text" Layout.alignment: Qt.AlignHCenter | Qt.AlignTop Layout.margins: 5 background: Rectangle { implicitWidth: 200 implicitHeight: 40 border.color: singleline.focus ? "#21be2b" : "lightgray" color: singleline.focus ? "lightgray" : "transparent" } } TextArea { id: multiline placeholderText: "Initial text\n...\n...\n" Layout.alignment: Qt.AlignLeft Layout.fillWidth: true Layout.fillHeight: true Layout.margins: 5 background: Rectangle { implicitWidth: 200 implicitHeight: 100 border.color: multiline.focus ? "#21be2b" : "lightgray" color: multiline.focus ? "lightgray" : "transparent" } } } }
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.