有没有办法使用锚点来定位QML元素而不在布局中生成警告?

Is there a way to use anchors to position QML elements without generating warnings in a Layout?

提问人:Sunidhi Kumari 提问时间:5/30/2023 最后编辑:iam_peterSunidhi Kumari 更新时间:5/30/2023 访问量:43

问:

我正在使用带有 Layout 内部元素的锚点将元素从中心放置在各自的位置,但我面临警告(我知道如果我们将锚点与布局一起使用,它会引发警告),但我想找到一种方法来消除这些警告。

RowLayout {
    id: rowFirst
    spacing: 5
    anchors.centerIn: parent

    Label {
        id: rgeValue
        text: "0"
    }

    Label {
        id: erUnit
        anchors.centerIn: parent
        anchors.horizontalCenterOffset: rgeValue.width / 2 + 5
        anchors.verticalCenterOffset: rgeValue.height / 2 - rgeValueUnit.height
        text: "V"
    }
}

从设计的角度来看,我不应该在布局中使用边距和填充。

布局 QML 定位

评论


答:

0赞 Jürgen Lutz 5/30/2023 #1

您可以通过将项目包装到另一个项目作为容器来消除警告。尽管如此,布局还是负责或将您的包装项目放入其单元格中。

RowLayout {
    id: rowFirst

    spacing: 5
    anchors.centerIn:  parent

    Item {
        Layout.fillHeight: true
        Layout.fillWidth: true

        Label {
            id: rgeValue
            text:  "0"
        }
    }

    Item {
        Layout.fillHeight: true
        Layout.fillWidth: true

        Label {
            id: rgeValueUnit
            text:  "V"
        }
    }
    
    Item {
        Layout.fillHeight: true
        Layout.fillWidth: true

        Label{
            id: erUnit

            anchors.centerIn:  parent
            anchors.horizontalCenterOffset: rgeValue.width/2+5
            anchors.verticalCenterOffset: rgeValue.height/2-rgeValueUnit.height

            text:"V"

        }
    }
}

正如@StephenQuan中提到的,这将有助于更好地了解您想要实现的目标。对我来说,你想以一种奇怪的方式使用布局。

1赞 Stephen Quan 5/30/2023 #2

如果父级是 RowLayout、ColumnLayout,则不应在子级中使用定位。子级应使用 Layout 附加属性。或者,如果父项是 Item, Rectangle,则可以使用定位点。你不应该把两者混为一谈。

也许你对这个问题想得太多了。我模拟了以下内容,演示了如何使用最少的代码将标签居中在 RowLayout 中。我放了一个虚拟背景,以便您可以确认标签文本确实居中:

    RowLayout {
        anchors.centerIn: parent
        Label {
            Layout.preferredWidth: 100
            Layout.preferredHeight: 50
            background: Frame { }
            text: "0"
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
        }
        Label {
            Layout.preferredWidth: 100
            Layout.preferredHeight: 50
            background: Frame { }
            text: "V"
            horizontalAlignment: Text.AlignHCenter
            verticalAlignment: Text.AlignVCenter
        }
    }

您可以在线试用!

评论

1赞 Amfasis 5/31/2023
OP 似乎希望第一个标签的大小是第二个标签的两倍,为此他可以调整。甚至可以在两个标签上使用,在这种情况下,将用作权重preferredWidthfillWidth: truepreferredWidth