main.qml
import QtQuick 2.12 import QtQuick.Window 2.12 import QtQml.Models 2.12 Window { visible: true 640 height: 480 title: qsTr("Hello World") FlowView { 300 height: 400 columns: 2 spacing: 10 model: ObjectModel { Rectangle { height: 95; 140; color: "red" } Rectangle { height: 30; 140; color: "green" } Rectangle { height: 200; 140; color: "blue" } Rectangle { height: 75; 140; color: "yellow" } Rectangle { height: 80; 140; color: "gray" } Rectangle { height: 300; 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方面的专家,而且非常乐于助人