开发者

How to swap elements in a qml grid?

开发者 https://www.devze.com 2023-04-04 12:16 出处:网络
I tried : var child = grid.children[slot1]; grid.children[slot1] = grid.children[slot2]; grid.children[slot2] = child;

I tried :

var child = grid.children[slot1];
grid.children[slot1] = grid.children[slot2];
grid.children[slot2] = child;

But it didn't work.

When reparentin开发者_开发百科g an element to the grid (element.parent = grid), it's effectively added, but there's no way to order them.

Should i use my own QML widget?


ListModel provides moving elements functionality, and you can use it in conjunction with a GridView (not just a grid).

GridView {
    id: grid
    anchors.fill: parent
    cellWidth: 32
    cellHeight: 32
    property bool loaded: false;

    model : ModelInheritingListModel {
    }

    delegate: MyDelegate {

    }

    onSwap: {
        var min = Math.min(slot1, slot2);
        var max = Math.max(slot1, slot2);
        grid.model.move(min, max, 1);
        grid.model.move(max-1, min, 1);
    }
}

And if you want to add animations in the delegate, when swapping:

Item {
    id: main
    width: grid.cellWidth
    height: grid.cellHeight

    Image {
        id: img
        x: main.x
        y: main.y

        /* In order to use animations, we can't use the main level component as
          it technically is the same item, so we need to animate the image.

          So we set the image's position relative to the parent instead, so
          we can animate its coordinates properly */
        parent: grid

        Behavior on x { NumberAnimation { duration: 400; easing.type: Easing.InOutCubic}}
        Behavior on y { NumberAnimation { duration: 400; easing.type: Easing.InOutCubic}}

        source: imagesource
        width: 32
        height: 32
    }
}

Notice the trick you have to use by reparenting...

Damn QML!

0

精彩评论

暂无评论...
验证码 换一张
取 消