在qml

时间:2016-09-19 07:13:03

标签: qt layout qml coordinates anchor

我遇到了qml的问题,当我使用锚来布局项时,它们的坐标没有被设置并且等于零。请参阅下面的代码段。

对于QML主播,这种行为是否正常?或者只是我做错了什么? 如何规避这一点?

Rectangle
{
    id: background
    objectName: "background"
    anchors.fill: parent
    color: "#06A0D4"
}

Rectangle
{
    id: ground
    objectName: "ground"
    anchors.left: background.left
    anchors.right: background.right
    anchors.bottom: background.bottom

    color: "#D47006"
    opacity: 0.4

    height: 50;
}

感谢。

2 个答案:

答案 0 :(得分:2)

这应该有效,即当我在qmlscene中运行以下代码时,文本显示Yellow rect: x=0, y=350, width=400, height=50,这正是我所期望的

import QtQuick 2.0

Item {
    width: 400
    height: 400

    Rectangle {
        id: background
        anchors.fill: parent
        color: "black"
    }

    Rectangle {
        anchors.left: background.left
        anchors.right: background.right
        anchors.bottom: background.bottom
        height: 50

        color: "yellow"

        Text {
            anchors.centerIn: parent

            text: "Yellow rect: x=" + parent.x + ", y=" + parent.y +
                ", width=" + parent.width + ", height=" + parent.height
        }
    }
}

答案 1 :(得分:1)

确实,它是未定义的。 我想这个问题在mapToItem内。 mapFromItem函数,它需要一个项目作为它的第一个参数 我只能猜测,如果没有明确设置,那些函数或相关函数用于计算坐标。

Window对象不是Item,而是QQuickWindow,因此这些函数不起作用。

Item内包裹所有内容应该可以解决问题,因为现在QML可以使用它的函数来计算位置。