How to fit and align items of GridView?
-
Hi. I wrote this code:
Window { visible: true width: 640 height: 480 title: qsTr("Hello World") GridView { id: area width: parent.width height: parent.height anchors.centerIn: parent anchors.margins: 20 cellWidth: width / 4 cellHeight: height / 4 model: 40 clip: true interactive: false delegate: Rectangle { id: rect width: area.cellWidth - 5 height: area.cellHeight - 5 color: 'red' Text { text: index color: 'white' anchors.centerIn: parent } MouseArea { anchors.fill: parent onClicked: rect.visible = false } } }
I set
model
as40
and I setinteractive
asfalse
. But I see just15
items like this:
I want to fit all items to screen. How can I do it? I didn't useGridLayout
because when I click the rectangle, I set visible of that rectangle asfalse
and GridLayout aligns all rectangles again. But I don't want it.
Also if I setmodel
ofGridView
as4
, I get this result:
But I want like this (4
items aligned to center):
How can I do them (to fit and align)? Thanks.UPDATE! - SOLVED!
import QtQuick 2.10 import QtQuick.Window 2.10 import QtQuick.Layouts 1.3 Window { visible: true width: 420 height: 720 title: qsTr("Hello World") GridView { id: area property int verticalChoice: (parent.width < parent.height) ? 4 : model / 4 property int horizontalChoice: (parent.width < parent.height) ? model / 4 : 4 width: (model < 8) ? 2 * cellWidth : cellWidth * verticalChoice height: (model < 8) ? 2 * cellHeight : cellHeight * horizontalChoice anchors.centerIn: parent cellWidth: (parent.width / verticalChoice) cellHeight: (parent.height / horizontalChoice) model: 8 clip: true interactive: false delegate: Item { width: area.cellWidth height: area.cellHeight Rectangle { id: rect anchors { fill: parent margins: 5 } color: 'red' Text { text: index color: 'white' anchors.centerIn: parent } } } } }
But
anchors.centerIn: parent
isn't working. -
@Ibrahim
you need to calculate the size of the GridView yourself based on the desired values/behavior.
And then center it in the parent (anchors.centerIn: parent
).To show all 40 items, you of course need to also adapt the cellSize dynamically.
-
@raven-worx thanks, how can I set cellSize? Is this a property? Because I couldn't find it.
-
@Ibrahim said in How to fit and align items of GridView?:
@raven-worx thanks, how can I set cellSize? Is this a property? Because I couldn't find it.
you are already using it in the code you've posted?! (cellWidth / cellHeight)