首页 > 解决方案 > QML: Implement custom control with rectangles

问题描述

enter image description here

I want to implement one control with 7 layers of rectangle. Top and bottom 2 rectangles are of the same size. But middle 3 rectangles are 1/3rd of width of the top and bottom 2 rectangles also two of such sets. The spacing between the rectangles will remain same.

How can it be achieved using the minimal code in QML. ( i.e. with 1 repeater or nested repeaters or some way thru models?)

I designed it using repetitive code by simply adding 10 rectangles and anchoring them properly but its not a good practice when things can be done with repeater / model.

标签: qmlqt5qqmlcomponent

解决方案


It's possible populate such rectangles with GridLayout. It works fine in 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);
        }
    }
}

推荐阅读