组件的QML屏幕坐标

时间:2014-01-30 10:53:30

标签: qt qml qt-quick

如果我有一个简单的,自包含的QML应用程序,我可以通过说

获得组件的绝对屏幕坐标
Component.onCompeted: {    
    var l = myThing.mapToItem(null, 0, 0)
    console.log("X: " + l.x + " y: " + l.y)
}

其中myThing是文件中任何其他组件的ID。但是,如果这个文件被合并到另一个QML文件中并且它定义的组件被重用,我就不再获得屏幕坐标了;我获得了相对于执行上述语句的组件的本地坐标。

如何获取项目的绝对屏幕坐标?

3 个答案:

答案 0 :(得分:6)

Component.onCompleted: {
    var globalCoordinares = myThing.mapToItem(myThing.parent, 0, 0)
    console.log("X: " + globalCoordinares.x + " y: " + globalCoordinares.y)
}

其中myThing.parent是您的主要组成部分。

答案 1 :(得分:1)

这是一个快速而又非常糟糕的解决方案。注意:这只是经过了轻微的测试,但到目前为止似乎都有效。我不建议在生产应用程序中使用它,因为它是一个完整的黑客,可能会在某些时候中断。

ApplicationWindow {
    id: mainWindow
    visible: true
    width: 640
    height: 480
    x: 150.0
    y: 150.0
    title: qsTr("Hello World")

    Rectangle {
        id: lolRect
        height: 50
        width: 50
        anchors.centerIn: parent;

        Component.onCompleted: {

            function getGlobalCordinatesOfItem(item) {

                // Find the root QML Window.
                function getRootWindowForItem(item) {
                    var cItem = item.parent;
                    if (cItem) {
                        return getRootWindowForItem(cItem);
                    } else {

                        // Path to the root items ApplicationWindow
                        var rootWindow = item.data[0].target;
                        if (rootWindow && rootWindow.toString().indexOf("ApplicationWindow") !== -1) {
                            return rootWindow;
                        } else {
                            console.exception("Unable to find root window!");
                            return null;
                        }
                    }
                }

                // Calculate the items position.
                var rootWindow = getRootWindowForItem(item);
                if (rootWindow) {
                    return Qt.point(rootWindow.x + lolRect.x,
                                    rootWindow.y + lolRect.y);
                } else {
                    return null;
                }
            }

            // Print the result.
            console.log(getGlobalCordinatesOfItem(this));
        }
    }
}

答案 2 :(得分:0)

从Qt 5.7开始,有Item.mapToGlobal

Component.onCompleted: {
    var globalCoordinares = mapToGlobal(0, 0)
    console.log("X: " + globalCoordinares.x + " y: " + globalCoordinares.y)
}