首页 文章

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

提问于
浏览
0

我想将所有矩形都装入 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)
      }
    }
  }
}

我将 modelGridView 设置为 40 ,并将 interactive 设置为 false . 但我只看到 15 这样的项目:

image.png

我也写了 anchors.centerIn: parent 但它没有运行 . 我该怎么做(适合和对齐)?

1 回答

  • 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
            }
        }
    }
    

相关问题