【问题标题】:QtQuick layout marginsQtQuick 布局边距
【发布时间】:2017-05-10 19:20:32
【问题描述】:

有什么方法可以去除 QML Layout 组件中的开始和结束边距?

这是一个带有几个孩子的 ColumnLayout 示例。问题是如何删除那些顶部和底部边距并沿父布局的整个高度重新分布所有子级。

ColumnLayout {
    id: dotColumn
    anchors.horizontalCenter: bg.horizontalCenter
    height: root.height
    Repeater {
        id: repeater
        model: root.model

        Item {
            id: activeDot_container

            property int radius: 15
            width: radius * 2
            height: radius * 2

            Rectangle {
                anchors.centerIn: parent
                radius: parent.radius

                width: radius * 2
                height: radius * 2

                color: Palette.colors['deepPurple']['500']
            }
        }
    }
}

【问题讨论】:

  • 好的,你必须至少向我们展示你的代码,这样我们才能帮助你。
  • @folibis 我的错。附上代码。
  • 你的代码不完整,所以我只能假设如何解决。尝试将Layout.alignment: Qt.AlignTop添加到activeDot_container项目
  • @folibis 但这样我只能在列底部获得更大的边距......

标签: qt layout qml qtquick2 qt-quick


【解决方案1】:

您不能将 Layout 中的项目同时上下对齐。作为一种解决方法,您可以将带有变量 y 的项目放入容器中,如下所示:

Window {
    visible: true
    visibility: Window.Maximized

    ColumnLayout {
        anchors.horizontalCenter: parent.horizontalCenter
        height: parent.height
        spacing:1
        Repeater {
            id: repeater
            model: 10
            Rectangle {
                color: "green"
                property int radius: 15
                width: radius
                Layout.fillHeight: true
                Rectangle {
                    anchors.horizontalCenter: parent.horizontalCenter
                    y: index * (parent.height - height) / (repeater.count - 1)
                    radius: parent.radius
                    width: radius * 2
                    height: radius * 2
                    color: "blue"
                }
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    经过几次布局定位实验后,我提出了以下解决方案。

    假设我要消除的边距大小为布局子级间距的一半,我们可以为布局组件的开头和结尾设置负边距,将其拉伸到第一个和最后一个子级在布局的开始/结束时对齐.

    我用来计算边距的函数:

    function getMargin() {
      var height = root.height;
      var spacing = (height - root.radius * 2 * model.length) / model.length;
      return spacing / 2;
    }
    

    root 是 Layout 组件的父级,root.radius*2 表示布局子项的大小,可以替换为另一个子维度,model.length 代表子级数。

    那么我们就可以为 Layout 组件设置锚点,并设置相应的边距。

    ColumnLayout {
        anchors.top: root.top
        anchors.bottom: root.bottom
        anchors.topMargin: -1 * getMargin()
        anchors.bottomMargin: -1 * getMargin()
        Repeater {
            model: root.model
            Item {
                property int radius: root.radius
                width: radius * 2
                height: radius * 2
                /* more code */
            }
        }
    }
    

    附:通过用左/右替换布局顶部/底部锚点,可以将相同的解决方案应用于 RowLayout。

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 1970-01-01
      • 2018-08-28
      • 2013-09-19
      • 2013-11-23
      • 2013-08-28
      • 2012-10-12
      • 2020-02-05
      • 2018-09-03
      相关资源
      最近更新 更多