QML的GridLayout如何在特定的行和列中放置一个矩形?

How to put a rectangle in a particular row and column in GridLayout of QML?

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1  // GridLayout

Window
{
    visible: true

    height: 700; width: 1000

    GridLayout
    {
        id: gridLayout
        rows: 15;
        columns: 15;
        rowSpacing: 0;    columnSpacing: 0

        property int secondScreenOptionsOpacity: 0

        property int hmmiButtonRow: 0
        property int hmmiButtonCol: 0

        Rectangle
        {
            id: hmmi;
            Layout.row: gridLayout.hmmiButtonRow; Layout.column: gridLayout.hmmiButtonCol;
            height: 70; width: 150; color: "pink";
            Layout.alignment: Qt.AlignTop
            Text { text: "HMMI"; anchors.centerIn: parent }
            MouseArea {anchors.fill: parent; onClicked: mainScreenFunctionality.hmmiControlButton()}
        }

        property int optionsButtonRow: 1
        property int optionsButtonCol: 0

        Rectangle
        {
            id: optionsButton;
            Layout.row: gridLayout.optionsButtonRow; Layout.column: gridLayout.optionsButtonCol;
            height: 70; width: 150; color: "red"
            Layout.alignment: Qt.AlignBottom
            Text { text: "Options..."; anchors.centerIn: parent }
            MouseArea { anchors.fill: parent; onClicked: mainScreenFunctionality.optionsButton() }
        }

        property int eulerWidgetRow: 1
        property int eulerWidgetCol: 11

        Rectangle
        {
            id: eulerWidgetControl;
            Layout.row :gridLayout.eulerWidgetRow; Layout.column: gridLayout.eulerWidgetCol;
            height: 140; width: 140; color: "yellow"
            Layout.columnSpan: 2; Layout.rowSpan: 2
            Layout.alignment: Qt.AlignRight
            Text { text: "euler"; anchors.centerIn: parent }
        }
    }
}

尽管我已经指定了第 1 行和第 11 列,但请查看显示黄色矩形的位置:


红色和黄色矩形之间必须空space。
如何在QML的GridLayout中将矩形放在特定的行和列中?


标题 ##

anchors.fill: parent 添加到 GridLayout 会执行以下操作:


There has to be empty space between the red and yellow rectangles.

仅当红色和黄色矩形之间的列宽大于零时。在您的代码中,第 1 ~ 10 列未指定,因此它们的宽度均为零。这就是空白(列)不显示的原因。要解决这个问题,您可以像这样向 GridLayout 添加一些不可见的列:

GridLayout {
    //your code ...

    Repeater {
        model: 9
        delegate: Item {
            width: 10; height: 10
            Layout.row: 1
            Layout.column: index + 1
    }
}

anchors.fill: parent 添加到 GridLayout 显示矩形之间的空白区域,这是 GridLayout 中最强大的功能之一:在网格中动态排列项目。如果我们将不可见的列更改为黑色矩形:

GridLayout {
    //your code...

    Repeater {
        model: 9
        delegate: Rectangle {
            width: 10; height: 10
            Layout.row: 1
            Layout.column: index + 1
            color: "black"
    }
}

可以清楚的看到,当GridLayout的宽度改变时(比如拖动window的边框),矩形之间的间距会自动改变