【问题标题】:QML stack ColumnLayout children on top of each other?QML 将 ColumnLayout 子项堆叠在一起?
【发布时间】:2017-07-20 10:45:22
【问题描述】:

我是 QML 的新手,所以我可能会问一些显而易见的问题。我正在努力将 ColumnLayout 中的元素堆叠在一起。他们之间的距离太大了,我无能为力。详情见截图:

这是实际的 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 像素。

谢谢

【问题讨论】:

  • 这不是this问题的重复吗?
  • @BaCaRoZzo 我当然会认为这是一个比公认答案更好的解决方案。
  • @Mitch 好吧,还有 another 重复的问题/答案与 Grecko 完全相同的话(找不到)所以是的,这是“公认的方式”。此外,在任何 Layout 中具有 marginsalignment 属性似乎与“如果您不需要管理职位,布局是件好事”的答案陈述相冲突。
  • 我认为你是对的,这是一个骗局,但另一个答案需要整理一下,我会在那里发表评论。

标签: qt qml qtquick2


【解决方案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 对您有帮助

【讨论】:

  • 这适用于提问者指定的用途,但仍然没有教他们正确使用 ColumnLayout 的方法。一旦掌握了 QML 中的布局,它就是一件方便而强大的东西。也许您还可以通过使用 ColumnLayout 提供实现提问者目标的正确方法,以便可以比较两个选项。简单地声称一种方法优于另一种方法是不对的
猜你喜欢
  • 1970-01-01
  • 2015-08-19
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 2022-01-10
  • 2017-11-21
相关资源
最近更新 更多