QML:使用矩形实现自定义控件

QML: Implement custom control with rectangles

我想实现一个7层矩形的控件。顶部和底部的 2 个矩形大小相同。但是中间的 3 个矩形是顶部和底部 2 个矩形宽度的 1/3,也是两个这样的集合。矩形之间的间距将保持不变。

如何使用QML中的最少代码实现。 (即使用 1 个中继器或嵌套中继器或某种方式通过模型?)

我通过简单地添加 10 个矩形并正确锚定它们来使用重复代码来设计它,但是当事情可以用中继器/模型完成时,这不是一个好的做法。

可以用 GridLayout 填充此类矩形。它在 Qml Online App.

中运行良好
import QtQuick 2.3
import QtQuick.Layouts 1.12

GridLayout {
    Repeater {
        model: [{row: 0, column: 0, columnSpan: 3},
                {row: 1, column: 0, columnSpan: 3},
                {row: 2, column: 0, columnSpan: 1},
                {row: 2, column: 2, columnSpan: 1},
                {row: 3, column: 0, columnSpan: 1},
                {row: 3, column: 2, columnSpan: 1},
                {row: 4, column: 0, columnSpan: 1},
                {row: 4, column: 2, columnSpan: 1},
                {row: 5, column: 0, columnSpan: 3},
                {row: 6, column: 0, columnSpan: 3}]
                
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            Layout.row: modelData.row
            Layout.column: modelData.column
            Layout.rowSpan: 1
            Layout.columnSpan: modelData.columnSpan
            Layout.preferredWidth: Layout.columnSpan
            Layout.preferredHeight: Layout.rowSpan
            
            color: Qt.rgba(Math.random(), Math.random(), Math.random(), 1);
        }
    }
}

您可以使用ListView for populating the given rectangles as delegates. You just need to handle the delegates in this case. Define two delegates as required and assign them to model of ListView based on their index as in given topic: Different delegates for QML ListView

试试这个

Component{
    id:rec2
    Item{
        property bool flag: true
        width:300
        height:20
        Repeater{
            model:!flag?1:2
        Rectangle{
            anchors.left: (flag && index==1)?parent.left:undefined
            anchors.right: (flag && index==0)?parent.right:undefined
            color: "transparent"
            border.color: "black"
            border.width: 3
            height: parent.height
            width: (flag)?(parent.width/3):parent.width
        }
        }

    }
}

Column{
    anchors.centerIn: parent
    spacing: 10
    Repeater{
        id:repeter
        model: [false,false,true,true,true,false,false]
        Loader{
            sourceComponent: rec2
            onLoaded: item.flag=repeter.model[index]
        }
    }
}