Drag and Drop within a ListView or a Column

  • I wanted to create a simple list of buttons that the user can reorder by dragging them with the mouse. Looking at the drag and drop example with the GridView [1] I first tried to recreate it using a simple Column with a repeater and a model, but I never got it working. Since the example uses a view I then tried with ListView, here is what I ended up with:

    import QtQuick 2.5
    import QtQuick.Window 2.2
    import QtQml.Models 2.2
    Window {
      id: root
      visible: true
      width: 100
      height: 200
      DelegateModel {
        id: visualModel
        model: ListModel {
          id: model
          ListElement { name: "red"; value: "#f00" }
          ListElement { name: "green"; value: "#0f0" }
          ListElement { name: "blue"; value: "#00f" }
        delegate: MouseArea {
          id: mouseArea
          property int visualIndex: DelegateModel.itemsIndex
          width: 80
          height: 20
          hoverEnabled: true
          drag.target: rect
          Rectangle {
            id: rect
            radius: 6
            width: 78
            height: 18
            color: model.value
            Drag.active: mouseArea.drag.active
            Drag.source: mouseArea
            Drag.hotSpot.x: width / 2
            Drag.hotSpot.y: height / 2
          DropArea {
            anchors {
              fill: parent
            onEntered: {
              var from = drag.source.visualIndex
              var to = mouseArea.visualIndex
              console.log("From " + from + " to " + to)
              visualModel.items.move(from, to)
      ListView {
        id: list
        anchors {
          centerIn: parent
          fill: parent
        interactive: false
        displaced: Transition {
            NumberAnimation { properties: "x,y"; easing.type: Easing.OutQuad }
        model: visualModel

    It works, but does not reposition the item dragged by the user after releasing the mouse button. So here are my two questions:

    • Is it possible to implement rearranging by drag and drop within a simple Column? If not what differs the different Views from the Row / Column items so that they can work with drag and drop?

    • I could not figure out why after releasing the rectangles are automatically repositioned in the grid in the Qt example: If you drag a rectangle just away from the others and not on another rectangle onEntered is called on the same Drop are to which the Rectangle belongs. This also happens in my code, but the Item does not get repositioned afterwards, why?

    [1] http://doc.qt.io/qt-5/qtquick-draganddrop-example.html

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.