QML - 如何拟合和对齐GridView的项目?

时间:2018-02-19 18:42:24

标签: qt gridview qml

我想将所有矩形都放入GridView。我没有使用GridLayout,因为当我从GridLayout中移除一个矩形时,它们会再次与GridLayout对齐。
所以我使用了GridView和我的代码:

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

    // If device orientation is vertical, GridView shall be 4x(model/4)
    property int verticalChoice: (parent.width < parent.height) ? 4 : 10
    //If device orientation is horizontal, GridView shall be (model/(model/4))x4
    property int horizontalChoice: (parent.width > parent.height) ? 10 : 4

    width: cellWidth * verticalChoice
    height: cellHeight * horizontalChoice
    anchors.centerIn: parent

    cellWidth: (parent.width / verticalChoice)
    cellHeight: (parent.height / horizontalChoice)

    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.destroy(1000)
      }
    }
  }
}

我将model的{​​{1}}设为GridView,并将40设为interactive。但我只看到false这样的项目:
image.png
我也写了15,但它没有运行。我该怎么做(适合和对齐)?

1 个答案:

答案 0 :(得分:1)

对于项目数量,您只需在horizontalChoice的分配中出错,设置4 * 4网格而不是10 * 4:

property int verticalChoice: (parent.width < parent.height) ? 4 : 10
property int horizontalChoice: (parent.width < parent.height) ? 10 : 4

对于居中问题,anchors.centerIn: parent实际上按预期工作,但由于您指定的委托比cellWidth / cellWidth小5px,因此您的空间为5px右下角。

为防止这种情况发生,您可以使用换行Item(据我所知GridView没有任何spacing属性):

delegate: Item {
    width: area.cellWidth
    height: area.cellHeight
    Rectangle {
        color: 'red'
        anchors {
            fill: parent
            margins: 5
        }

        Text {
            text: index
            color: 'white'
            anchors.centerIn: parent
        }
    }
}