2011-06-02 63 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" 
    } 
} 
相关问题