Items not correctly spread across GridLayout

扶醉桌前 提交于 2019-12-06 09:26:58

The attached properties of a Layout ensures that the Items contained are correctly sized w.r.t. the given constraints.

Items can be stretched to fill the available space (fillWidth/fillHeight), forced to not shrink under a certain value (minimumWidth/minimumHeight) or not enlarge over a certain other value (maximumWidth/maximumHeight). You can also force an Item to occupy more than one row/column (rowSpan/columnSpan) and to assume a specific size (preferredWidth/preferredHeight which implies minimum == maximum).

The precedence is:

preferred <minimum/maximum < width/height

Setting a property to the left automatically discard any to the right. You can easily understand the reasoning behind this. This scheme can be somewhat "broken" by implicitWidth/implicitHeight since the size of any Item cannot shrink under these values. fill properties ensure that the Item fills the available space, according to the constrains above: if fill is not defined an Item cannot grow or shrink according to its constrains.

Now, if you want the Buttons to maintain they aspect and still stretch the grid, you can use an intermediate Item. While applying Layout attached properties to the external Item, the Buttons can be centerIn it and be unaffected.

Sample code:

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4

Window {
    width: 200; height: 200; minimumHeight: 100; visible: true

    GridLayout {
        anchors.fill: parent
        rows: 3
        columns: 3

        Repeater {
            model: 9

            Item {
                Layout.fillWidth: true
                Layout.fillHeight: true

                Button { anchors.centerIn: parent; width: 32; height: 32; text: index + 1 }
            }
        }
    }
}

Instead if you want the Buttons to fill the available space, just specify fillWidth/fillHeight. Since no other layout constraints are set (e.g. minimum*, maximum*) the Buttons correctly occupy all the available space. Here is the code above revisited. As expected, width and height are simply discarded:

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4

Window {
    width: 200; height: 200; minimumHeight: 100; visible: true

    GridLayout {
        anchors.fill: parent
        rows: 3
        columns: 3

        Repeater {
            model: 9

            Button {width: 32; height: 32; text: index + 1;   // 32? NOPE!
                Layout.fillWidth: true; Layout.fillHeight: true
            }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!