QML 動的ビュー順序設定チュートリアル 3 - ドラッグされた項目の移動
アプリケーションの次のステップでは、ドラッグされたアイテムをリスト内で移動させ、リストの順序を変更できるようにします。これを実現するために、アプリケーションに 3 つの新しい型、DelegateModel 、Drag 、DropArea を導入します。
Rectangle {
id: root
width: 300
height: 400
Component {
id: dragDelegate
MouseArea {
id: dragArea
property bool held: false
required property string name
required property string type
required property string size
required property int age
anchors {
left: parent?.left
right: parent?.right
}
height: content.height
drag.target: held ? content : undefined
drag.axis: Drag.YAxis
onPressAndHold: held = true
onReleased: held = false
Rectangle {
id: content
Drag.active: dragArea.held
Drag.source: dragArea
Drag.hotSpot.x: width / 2
Drag.hotSpot.y: height / 2
}
DropArea {
anchors {
fill: parent
margins: 10
}
onEntered: (drag) => {
visualModel.items.move(
drag.source.DelegateModel.itemsIndex,
dragArea.DelegateModel.itemsIndex)
}
}
}
}
}手順
ビューの順序を変更するには、あるアイテムが別のアイテムの上にドラッグされたタイミングを特定する必要があります。「Drag」アタッチドプロパティを使用すると、それがアタッチされているアイテムが移動するたびに、シーングラフに送信されるイベントを生成できます。
Drag.active: dragArea.held
Drag.source: dragArea
Drag.hotSpot.x: width / 2
Drag.hotSpot.y: height / 2Dragイベントはactiveプロパティがtrueの間のみ送信されるため、この例では、デリゲートが押された時点で最初のイベントが送信され、ドラッグ中に追加のイベントが送信されます。hotSpot プロパティは、ドラッグ対象アイテム内(この例ではアイテムの中心)におけるドラッグイベントの相対位置を指定します。
次に、各ビューアイテムでDropArea を使用して、ドラッグ対象アイテムのホットスポットが別のアイテムと交差するタイミングを判定します。ドラッグ操作がこれらのDropAreasのいずれかに入った時点で、ドラッグ対象アイテムを、その上をドラッグしたアイテムのインデックス位置に移動させることができます。
DropArea {
anchors {
fill: parent
margins: 10
}
onEntered: (drag) => {
visualModel.items.move(
drag.source.DelegateModel.itemsIndex,
dragArea.DelegateModel.itemsIndex)
}
}ビュー内のアイテムを移動するには、DelegateModel を使用します。DelegateModel 型は、ビュータイプがモデルデータからデリゲートアイテムをインスタンス化する際に使用され、明示的に構築された場合、ListView に提供されるモデルアイテムをフィルタリングおよび並べ替えするために使用できます。DelegateModel のitems プロパティを使用すると、ビューのアイテムにアクセスでき、ソースモデルを変更することなく表示順序を変更することができます。 項目の現在の表示インデックスを特定するには、デリゲート項目のDelegateModel アタッチドプロパティにあるitemsIndex {itemsIndex}プロパティを使用します。
DelegateModel をListView で利用するには、これをビューのmodel プロパティにバインドし、model およびdelegate をDelegateModel にバインドします。
DelegateModel {
id: visualModel
model: PetsModel {}
delegate: dragDelegate
}
ListView {
id: view
anchors {
fill: parent
margins: 2
}
model: visualModel
spacing: 4
cacheBuffer: 50
}© 2026 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.