设置锚点

时间:2016-12-27 21:22:31

标签: layout qml qtquick2

我试图了解锚点在QML(Qt Quick 2.0)中的工作原理。我有一个像这样的简单项目:

AddButton.qml:

Item {

    Button {
        text: "ADD"
        width: 100
        height: 50
    }

}

我将其添加到主QML文件中:

main.qml:

Item {
    id: root
    width: 800
    height: 600

    AddButton {
        id: addButton
    }

}

这很好用。但是,只要我尝试使用锚点将按钮放在右下角,按钮就会消失:

main.qml:

Item {

    .....

    AddButton {
        id: addButton
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

}

只有在主QML文件级别设置宽度和高度时才会返回:

main.qml:

Item {

    .....

    AddButton {
        id: addButton
        width: 100
        height: 50
        anchors.right: parent.right
        anchors.bottom: parent.bottom
    }

}

所以我想知道,当我设置锚点时,为什么按钮会消失?有没有办法让它工作而不设置主QML文件中的宽度和高度(基本上是为了使它使用AddButton.qml中设置的任何大小?)

1 个答案:

答案 0 :(得分:3)

问题是封装Item没有明确的width height。在这种情况下,引擎指的是"自然" witdh / height,即implicitWidth / implicitHeight属性。在大多数情况下,即使在这种特定情况下,这些属性也恰好为零。因此,您的自定义类型具有零维度。 因此,AddButton.anchors.bottom实际上位于封装Button的顶部,而后者又突出了封装Item

这有两件事:

除非您想要隐藏Button的内部,否则您不需要将Button与项目封装起来。

如果后者是你的愿望,试试这个:

Item {
    width: 100 //give the object a dimension!
    height: 50

    Button {
        text: "ADD"
        anchors.fill: parent
    }
}

现在你可以锚定它,它不会被定位在其他地方。

相关问题