2016-11-24 45 views
0

下面是一个简单的例子:如何在QML中将RowLayout正确拆分为两个相等的字段?

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

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

这里是相同的例子通过从Text部件Layout.fillWidth: true

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相同。

回答

0

您可以使用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

是的,我知道这一点。但是如果我将间距设置为0以外的数字,或者我想要3个相同的字段呢?设置parent.width/2或3等等+手动添加间距的值到等式中感觉有点不好意思。 – Silex

+0

好吧,假设你有'RowLayout' 100px,并且你想把它分成3个相等的区域。你会为每个像素设置多少像素宽度?正如你所看到的,我没有设置最后一个'Rectangle'的宽度,所以它将填充所有剩余的空间,没有间距等。 – folibis

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 
} 
相关问题