2011-06-02 62 views
17

QML如何自動拉伸元素以使其所有子元素適合它?以及如何指定間距?例如,我想在文本週圍有一個矩形。矩形應該有一些內部空間。將元素拉伸以包含所有子元素

如果我寫下面那麼矩形的大小爲0,0。

Rectangle { 
    color: "gray" 
    anchors.centerIn: parent; 

    Text { 
     text: "Hello" 
    } 
} 

如果我試圖通過使用Column元素來解決這個問題,如How to make QML items to grow to fit contents?建議的話,我打通了整個窗口/父列,

Column { 
    anchors.centerIn: parent 

    Rectangle { 
     color: "gray" 
     anchors.fill: parent 
    } 

    Text { 
     anchors.centerIn: parent 
     text: "Hello" 
    } 
} 

編輯:

我也嘗試過使用Flow元素代替Column,但後來我通過了wh ole窗口/父母。

回答

36

您可以使用此childrenRect屬性:

import QtQuick 1.1 

Rectangle { 
    width: 320 
    height: 200 

    Rectangle { 
     color: "BurlyWood" 
     anchors.centerIn: parent 
     width: childrenRect.width + 20 
     height: childrenRect.height + 20 

     Text { 
      id: hello 
      x: 10 
      y: 10 
      text: "Hello" 
     } 

     Text { 
      anchors.left: hello.right 
      anchors.leftMargin: 10 
      anchors.top: hello.top 
      text: "World" 
     } 
    } 
} 

但是請注意,使用childrenRect結合在其中一個直接孩子中使用anchors.centerIn: parent會產生有關綁定循環的警告。

+0

'main.qml:6:ReferenceError:childrenRect is not defined'。問題是什麼? Qt 5.3,QtQuick 2.3 – ManuelSchneid3r 2016-01-02 15:00:44

+0

@ ManuelSchneid3r嗯,我不能重現你的問題。我只是用Qt 5.5來測試它,在將導入改爲QtQuick 2.3之後,用'qmlscene'運行上面的代碼。工作很好。 – 2016-01-03 15:20:36

+0

問題是我在'Window'scope中試過。在那裏,childrenRect沒有定義。 – ManuelSchneid3r 2016-01-03 19:55:07

4

設置widthheight手工作品,但有點難看:

Rectangle { 
    color: "gray" 
    width: label.width+20 
    height: label.height+20 
    anchors.centerIn: parent 

    Text { 
     id: label 
     anchors.centerIn: parent 
     text: "Hello" 
    } 
} 
相關問題