QML堆栈ColumnLayout的孩子们在彼此之上?

时间:2017-07-20 10:45:23

标签: qt qml qtquick2

我是QML的新手,所以我可能会问一些明显的问题。我正在努力将ColumnLayout中的元素堆叠在一起。他们之间的间距太大我无能为力。有关详细信息,请参见屏幕截图:

enter image description here

这是实际的QML:

ColumnLayout {
    anchors.fill: parent
    spacing: 0

    Rectangle {
        color: "blue"
        Layout.fillWidth: true
        height: 50
    }

    Rectangle {
        color: "red"
        Layout.fillWidth: true
        height: 50
    }

    Rectangle {
        color: "yellow"
        Layout.fillWidth: true
        height: 50
    }
}

我要做的是让矩形从上到下对齐,并且它们之间的间距可能是2-3像素。

由于

1 个答案:

答案 0 :(得分:1)

如果您将填充移除到父级并将其填充到宽度

,则您的代码将正常工作
anchors.left: parent.left
anchors.right: parent.right 

之后代码将如下所示

ColumnLayout {
    anchors.left: parent.left
    anchors.right: parent.right
    spacing: 2 //spacing between items in layout
    Rectangle {
        color: "blue"
        Layout.fillWidth: true
        height: 50
    }
    Rectangle {
    ...
    }
    Rectangle {
    ...
    }
}

通过这样做,您将授予ColumnLayout管理自己height的权利。它的高度与孩子的身高有关,不会伸展到父母的身高。

另一种方法是通过anchor

管理商品
Item {
  id: item1
}
Item {
  id: item2
  anchor.top: item1.bottom
  anchor.topMargin: 2 
}
Item {
  id: item3
  anchor.top: item2.bottom
  anchor.topMargin: 3 
}

如果您不需要在布局内管理以特定方式项目的位置,那么布局就会很好。

此外,您还可以查看Use Case - Positioners and Layouts In QML

相关问题