2016-11-24 44 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 
} 
相關問題