Qt实现原生Flow实现不了的Item错误排列效果,类似淘宝商品展示

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQml.Models 2.12
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    FlowView {
        width: 300
        height: 400
        columns: 2
        spacing: 10
        model: ObjectModel {
            Rectangle { height: 95; width: 140; color: "red" }
            Rectangle { height: 30; width: 140; color: "green" }
            Rectangle { height: 200; width: 140; color: "blue" }
            Rectangle { height: 75; width: 140; color: "yellow" }
            Rectangle { height: 80; width: 140; color: "gray" }
            Rectangle { height: 300; width: 140; color: "pink" }
        }
    }
}

FlowView.qml

import QtQuick 2.12
import QtQuick.Controls 2.12

Item {
    id: root
    property int columns: 2
    property var model
    property int rowSpacing
    property int spacing
    clip: true
    property var geomeory: []

    ScrollView {
        anchors.fill: parent
        Repeater {
            model: root.model
            onItemAdded:  {//(int index, Item item)
                if (index % 2 === 0) { //偶数放左边
                    if (index - 2 >= 0) { //上面有,坐标累加
                        item.x = spacing
                        item.y = spacing + geomeory[index - 2].y + geomeory[index - 2].height
                    } else { //上面没有,直接放
                        item.x = spacing
                        item.y = spacing
                    }
                } else { //奇数放右边
                    if (index - 2 >= 0) { //上面有,坐标累加
                        item.x = spacing + geomeory[index - 1].x + geomeory[index - 1].width
                        item.y = spacing + geomeory[index - 2].y + geomeory[index - 2].height
                    } else { //上面没有,直接放. 奇数左边肯定有一个,直接用index - 1
                        item.x = spacing + geomeory[index - 1].x + geomeory[index - 1].width
                        item.y = spacing
                    }
                }
                geomeory.push(item)
                geomeory = geomeory
            }
            onItemRemoved: { //(int index, Item item)
                //TODO
            }
        }
    }
}

效果图如下:

 感谢支持的涛哥,放一波 @威武的涛哥 知乎专栏链接,Qt方面的专家,而且非常乐于助人

https://zhuanlan.zhihu.com/TaoQt

posted @ 2019-11-13 11:19  鬼谷子com  阅读(314)  评论(0编辑  收藏  举报