2011-09-13 54 views
4

我想:如何交換的QML網格元素?

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

但沒有奏效。

將元素重新分配給網格(element.parent = grid)時,會有效地添加元素,但無法對它們進行排序。

我應該用我自己的QML插件?

回答

7

ListModel提供了移動元素功能,您可以將它與GridView(不只是一個網格)結合使用。

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); 
    } 
} 

如果你想在委託添加動畫,交換時:

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 
    } 
} 

通知你必須重排根使用的伎倆......

該死QML!