如何在QML中将RowLayout正确拆分为两个相等的字段?

问题描述 投票:1回答:2

这是一个简单的例子:

RowLayout {
   spacing: 5

   ColumnLayout {
      Text {
         Layout.fillWidth: true
         text: qsTr("Some text")
      }
      Rectangle {
         Layout.fillWidth: true
         height: 100
         color: "red"
      }
   }

   ColumnLayout {
      Text {
         Layout.fillWidth: true
         text: qsTr("Some more text")
      }
      Rectangle {
         Layout.fillWidth: true
         height: 50
         color: "red"
      }
   }
}

这将在widthRowLayout产生两个相等的字段,但为什么我必须为所有孩子指定Layout.fillWidth: true

以下是从Layout.fillWidth: true组件中删除Text的相同示例:

RowLayout {
   spacing: 5

   ColumnLayout {
      Text {
         text: qsTr("Some text")
      }
      Rectangle {
         Layout.fillWidth: true
         height: 100
         color: "red"
      }
   }

   ColumnLayout {
      Text {
         text: qsTr("Some more text")
      }
      Rectangle {
         Layout.fillWidth: true
         height: 50
         color: "red"
      }
   }
}

这里RowLayout的两个领域在width不会相同。

qt qml qt5
2个回答
2
投票

您可以使用Layout.preferredWidth来设置行元素的大小(绝对或相对):

RowLayout {
    anchors.fill: parent
    spacing: 0
    Rectangle {
        Layout.preferredWidth: parent.width / 2
        Layout.fillHeight: true
        color: "green"
    }
    Rectangle {
        Layout.fillWidth: true
        Layout.fillHeight: true
        color: "yellow"
    }
}

0
投票

使用具有两列的GridLayout可能更好。

Rectangle {
    height: 20
    width: 300
    color: "green"
    GridLayout {
        anchors.fill: parent
        columns: 2
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "red"
        }
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "blue"
        }
    } //GridLayout
}
© www.soinside.com 2019 - 2024. All rights reserved.