Qt 获取QuickControl的屏幕坐标

Qt 获取QuickControl的屏幕坐标,qt,qml,coordinates,qtquick2,qtquickcontrols,Qt,Qml,Coordinates,Qtquick2,Qtquickcontrols,我必须设置QWindow的x,y坐标。此QWindow必须获取myMain窗口中QuickControl的屏幕坐标 如何在QML中获取QuickControl的全局屏幕坐标?对于x和y坐标相对于所有项目的父项,但顶部项目除外(又名窗口),您至少可以通过父链到主窗口来获取它们,这些变量表示相对于屏幕的位置 在通过父链的过程中,这是一个加减的问题,确实很烦人,但我不知道是否存在其他解决方案。正如@BaCaRoZzo所提到的,使用mapToItem()/mapFromItem()函数: import

我必须设置
QWindow
的x,y坐标。此
QWindow
必须获取my
Main窗口中
QuickControl
的屏幕坐标


如何在QML中获取
QuickControl
的全局屏幕坐标?

对于
x
y
坐标相对于所有项目的父项,但顶部项目除外(又名
窗口
),您至少可以通过父链到主
窗口来获取它们,这些变量表示相对于
屏幕的位置


在通过父链的过程中,这是一个加减的问题,确实很烦人,但我不知道是否存在其他解决方案。

正如@BaCaRoZzo所提到的,使用
mapToItem()
/
mapFromItem()
函数:

import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 1.0

Window {
    id: window
    width: 400
    height: 400
    visible: true

    Button {
        id: button
        text: "Button"
        x: 100
        y: 100

        readonly property point windowPos: button.mapToItem(null, 0, 0)
        readonly property point globalPos: Qt.point(windowPos.x + window.x, windowPos.y + window.y)
    }

    Column {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottom: parent.bottom

        Text {
            text: "Button position relative to window: x=" + button.windowPos.x + " y=" + button.windowPos.y
        }

        Text {
            text: "Button position relative to screen: x=" + button.globalPos.x + " y=" + button.globalPos.y
        }
    }
}
如for
mapToItem()
中所述:

将此项目坐标系中的点(x,y)或矩形(x,y,宽度,高度)映射到项目坐标系,并返回与映射坐标匹配的点或矩形

如果项为空值,则将点或rect映射到根QML视图的坐标系

这给了我们
windowPos
。为了获得控件相对于屏幕本身的位置,我们只需添加窗口的
x
y
位置


与OP聊天后,很明显他希望在C++中这样做。同样的原理也适用,在C++中,我们有更方便的窗口访问:

class Control : public QQuickItem
{
    Q_OBJECT
public:
    Control() {}
    ~Control() {}

public slots:
    void printGlobalPos() {
        qDebug() << mapToItem(Q_NULLPTR, QPointF(0, 0)) + window()->position();
    }
};
对象mapFromGlobal(实x、实y)

将全局坐标系中的点(x,y)映射到项目的坐标系,并返回与映射坐标匹配的点。
Qt 5.7中介绍了此QML方法。

对于内部
s,有
mapToItem
/
mapFromItem
函数<代码>屏幕
应该为顶级容器提供一些辅助功能。这很有意义。:-。。。在我看来,您可以使用
mapToItem
来缩短父链,但在获得项目的相对位置后,仍然需要获得到
屏幕的偏移量,因为
mapToItem
映射到最顶端(例如,
ApplicationWindow
)。我错了吗?谢谢,现在我能够读取相对于主窗口的x,y坐标。对于全局坐标,我尝试使用Window.x和Window.y添加,但没有效果,您能给我一个建议吗?运行我提供的示例并拖动窗口-全局坐标将更新。你试过了吗?这个快速控制应该是通用的,所以我不能使用任何ID,可以吗?对不起,我不明白你的意思。你说的是哪个控件?很抱歉描述不清楚,现在我需要QComboBox的全球位置。我可以使用
mapToItem(null,0,0)
获得相对于根元素的x,y坐标。如果我理解正确,我必须添加根元素的全局x,y坐标,但是我该怎么做呢?
qmlRegisterType<Control>("Types", 1, 0, "Control");
import QtQuick 2.0
import QtQuick.Window 2.0

import Types 1.0

Window {
    id: window
    width: 400
    height: 400
    visible: true

    Control {
        id: button
        x: 100
        y: 100
        width: 100
        height: 40

        MouseArea {
            anchors.fill: parent
            onClicked: button.printGlobalPos()
        }

        Rectangle {
            anchors.fill: parent
            color: "transparent"
            border.color: "darkorange"
        }
    }
}