【问题标题】:QML - How to fit and align items of GridView?QML - 如何适应和对齐 GridView 的项目?
【发布时间】:2018-02-19 18:42:24
【问题描述】:

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

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

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

【问题讨论】:

    标签: qt gridview qml


    【解决方案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
            }
        }
    }
    

    【讨论】:

    • 哦,谢谢,这是真的。好吧,为什么anchors.centerIn: parent 不运行?
    • 我像您的代码一样编辑了我的代码:gist.github.com/anonymous/9f219711985f8c69831ece5a7a02ab0f 但它不起作用。
    猜你喜欢
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2014-05-26
    • 2011-08-14
    • 2020-11-17
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多