Solved How can GridLayout be set to look like the following pictures in QML?
-
import QtQuick 2.8 import QtQuick.Controls 2.1 import QtQuick.Layout 1.2 Item{ Rectangle { GridLayout { id : grid anchors.fill: parent rows : 100 columns : 100 property double colMulti : grid.width / grid.columns property double rowMulti : grid.height / grid.rows function prefWidth(item){ return colMulti * item.Layout.columnSpan } function prefHeight(item){ return rowMulti * item.Layout.rowSpan } Rectangle { id : greenRect color : 'green' Layout.row : 0 Layout.column : 0 Layout.preferredWidth : grid.width Layout.preferredHeight : grid.height } Rectangle { color : 'red' Layout.row : 15 Layout.column: 2 Layout.preferredWidth : colMulti*20 Layout.preferredHeight : rowMulti*20 } Rectangle { color : 'yellow' Layout.row : 50 Layout.column: 2 Layout.preferredWidth : colMulti*20 Layout.preferredHeight : rowMulti*20 } Rectangle { color : 'white' Layout.row : 15 Layout.column: 75 Layout.preferredWidth : colMulti*20 Layout.preferredHeight : rowMulti*20 } Rectangle { id : greenRect color : 'black' Layout.row : 50 Layout.column: 75 Layout.preferredWidth : colMulti*20 Layout.preferredHeight : rowMulti*20 } } } }
-
Did you look here?; https://doc.qt.io/qt-5/qml-qtquick-layouts-gridlayout.html ~ you could have easily tweaked the given example by replacing
Text
elements withRectangle
.Here's how i'd do it;
import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Layouts 1.12 Window { visible: true width: 400 height: 300 color: "#5b9bd5" title: qsTr("Gridlayout example") GridLayout { columns: 2 rows: 2 columnSpacing: 100 rowSpacing: 100 anchors.centerIn: parent Rectangle { color: "#ed7d31"; width: 100; height: 60; radius: 10 Text { text: "1"; color: "white"; anchors.centerIn: parent } } Rectangle { color: "#ed7d31"; width: 100; height: 60; radius: 10 Text { text: "2"; color: "white";anchors.centerIn: parent } } Rectangle { color: "#ed7d31"; width: 100; height: 60; radius: 10 Text { text: "3"; color: "white"; anchors.centerIn: parent } } Rectangle { color: "#ed7d31"; width: 100; height: 60; radius: 10 Text { text: "4"; color: "white"; anchors.centerIn: parent } } } Text { id: hint font.pixelSize: 14 anchors.centerIn: parent text: "https://doc.qt.io/qt-5/qml-qtquick-layouts-gridlayout.html" } }
Or, not meaning to be a pedant, but this is literally much closer to what you're asking;
import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Layouts 1.12 Window { visible: true width: 460 height: 320 color: "white" title: qsTr("Gridlayout example") Rectangle { border { width: 4 color: "black" } color: "#00000000" anchors.fill: parent GridLayout { columns: 2; columnSpacing: 140 rows: 2; rowSpacing: 60 anchors { top: parent.top topMargin: 30 horizontalCenter: parent.horizontalCenter } Repeater { model: 4 Rectangle { color: "white"; width: 110; height: 90; border { width: 4; color: "black" }} } } } }