【问题标题】:QML can't anchor to item in layoutQML 无法锚定到布局中的项目
【发布时间】:2019-05-25 03:30:18
【问题描述】:

观察这个简单的例子:

import QtQuick 2.9
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.2

ApplicationWindow {
    visible: true
    width: 100
    height: 100

    Label {
        text: "foobar"

        anchors.bottom: row.top
        anchors.left: label1.right
    }

    RowLayout {
        id: row
        anchors.bottom: parent.bottom
        width: parent.width

        Label {
            id: label1
            text: "hello1"
            Layout.alignment: Qt.AlignLeft
        }
        Label {
            id: label2
            text: "hello2"
            Layout.alignment: Qt.AlignRight
        }
    }
}

我在行布局中有两个项目,我想将第三个标签锚定到其中一个。这就是我得到的:

我希望 foobar 更靠右,但这不是我得到的。

此外,我为标签设置的任何边距也将被忽略。

我可以锚定到窗口或 RowLayout,它会很好地工作,但由于某种原因,我不能锚定到布局内的项目。这是什么原因,有什么合适的解决方案?

【问题讨论】:

    标签: qt qml


    【解决方案1】:

    编译程序时会报错:Cannot anchor to an item that isn't a parent or sibling. Here's an answer,为什么不能锚定。我的解决方案是,我们将锚定在 row 的左侧,然后在行内以 label1 的宽度制作边距。

    这是截图。

    import QtQuick 2.9
    import QtQuick.Controls 2.2
    import QtQuick.Layouts 1.2
    
    ApplicationWindow {
        visible: true
        width: 100
        height: 100
    
        Label {
            color: "#b7087d"
            text: "foobar"
    
            anchors.bottom: row.top
            anchors.left: row.left
            anchors.leftMargin: label1.width
        }
    
        RowLayout {
            id: row
            anchors.bottom: parent.bottom
            width: parent.width
    
            Label {
                id: label1
                color: "#b22424"
                text: "hello1"
                Layout.alignment: Qt.AlignLeft
            }
            Label {
                id: label2
                color: "#1e62ce"
                text: "hello2"
                Layout.alignment: Qt.AlignRight
            }
        }
    }
    

    【讨论】:

    • 谢谢,我忘记了锚定功能。好吧,边距不是那么方便,所以我想我会重新考虑整个布局。
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2017-05-23
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2018-08-10
    • 2017-01-23
    相关资源
    最近更新 更多