qt - QML。如何为所有父空间拉伸(stretch)网格

标签 qt qml qtquick2

我有一个自定义按钮:

import QtQuick 2.0

Rectangle {
    id: xobutton
    width: 100
    height: 100
    property string label: "?"
    border.width: 2

    Text {
        id: xobuttonLabel
        text: label
        font.pointSize: 75
        anchors.centerIn: parent
    } 
}

它有一个父矩形:

Rectangle {
    width: 500
    height: 500

    Grid {
        anchors.centerIn: parent
        rows: 3; columns: 3; spacing: 0

        Repeater {
            model: 9
            Xobtn { }
        }
    } 
}

我需要拉伸(stretch)Grid中的所有按钮以获取父矩形中的所有可用空间。我怎样才能做到这一点?谢谢。

最佳答案

Grid 只是将项目放置在其中,并尊重项目的大小。要主动调整项目大小,您需要使用 GridLayout ,并告诉它如何使用 Layout attached properties 调整项目大小。 。所以你的代码变成这样,注释显示对你的代码的更改:

import QtQuick.Layouts 1.1 // needed for GridLayout

Rectangle {
    width: 500
    height: 500

    GridLayout {
        anchors.fill: parent // GridLayout must have the right size now
        rows: 3; columns: 3
        columnSpacing: 0; rowSpacing: 0 // changed from spacing: 0

        Repeater {
            model: 9
            Xobtn {
                // attached properties guiding resizing
                Layout.fillHeight: true
                Layout.fillWidth: true 
            }
        }
    }
}
<小时/>

如果您出于某种原因不想依赖QtQuick.Layouts,那么您必须自己计算宽度高度 ,但是如果您需要除统一网格之外的任何东西,例如:

        Xobtn {
            height: grid.parent.height / grid.columns - grid.spacing
            width: grid.parent.width / grid.rows - grid.spacing
        }

其中 grid网格的 ID。

关于qt - QML。如何为所有父空间拉伸(stretch)网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30415853/

相关文章:

qt - CMake、Qt 和 CMAKE_INCLUDE_PATH

javascript - 使用 qml 添加一个有条件的类

qml - 设置 RowLayout 的最大宽度

qt - 从 qml 中的 .txt 或 .csv 文件读取一行(Qt Quick)

c++ - 如何在 QQuickItem 上绘制 QQuickItem

C++/Qt:QCoreApplicationPrivate::sendPostedEvents 崩溃

c++ - 如何使用 Qt 到 Xlib 窗口绘制矩形

c++ - 将 somedialog.h 包含到项目的其他部分会使 ui_somedialog.h 对编译器不可见

qt - QML - MouseArea/MouseEvent 问题

python - PySide2 与 qml 作为 ui