首页 文章

QML中的视觉对象如何适合屏幕?

提问于
浏览
1

这是我的QML代码:

import QtQuick 2.10
import QtQuick.Window 2.10
import QtQuick.Layouts 1.3

Window {
  visible: true
  width: 640
  height: 480
  title: qsTr("Hello World")

  GridLayout {
    anchors.centerIn: parent
    anchors.margins: 8
    rowSpacing: 5
    columnSpacing: 5
    columns: 4

    Repeater {
      model: 12
      Rectangle {
        width: 100 / Screen.devicePixelRatio
        height: 100 / Screen.devicePixelRatio
        color: 'blue'

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

如果我设置的 Repeater12 model ,认为是好的这样的:
Image-1
但如果我设置的 Repeater model36 我得到这样的观点:
Image-2
我想所有的矩形是大小,并根据屏幕/窗口大小一致 . 我希望任何矩形都不会溢出不可见的空间 . 我该怎么做?

1 回答

  • 1

    如果您希望它占用所有可用的垂直空间,那么您必须计算每个矩形的高度:

    import QtQuick 2.10
    import QtQuick.Window 2.10
    import QtQuick.Layouts 1.3
    
    Window {
      id: win
      visible: true
      width: 640
      height: 480
      title: qsTr("Hello World")
    
      GridLayout {
        id: gl
        anchors.centerIn: parent
        anchors.margins: 8
        rowSpacing: 5
        columnSpacing: 5
        columns: 4
    
        readonly property real heighItem : {
                var rowCountEffective =  Math.round(repeater.count/gl.columns)
                var heightEffective = win.height-rowCountEffective*gl.rowSpacing - gl.anchors.topMargin -gl.anchors.bottomMargin
                return heightEffective/(rowCountEffective * Screen.devicePixelRatio)
            }
    
        Repeater {
          id: repeater
          model: 50
          Rectangle {
            width: 100 / Screen.devicePixelRatio
            height: gl.heighItem
            color: 'blue'    
            Text { anchors.centerIn: parent; text: index+1; color: 'white' }
          }
        }
      }
    }
    

    enter image description here

相关问题