QML mapToGlobal() 相对于屏幕或应用程序窗口

KMK*_*KMK 5 qt qml

我遇到过一些奇怪的行为。

项目的 mapToGlobal() 或 mapFromGlobal() 方法在坐标相对于什么方面似乎不一致。

对于某些项目,位置是相对于应用程序窗口的。

对于其他项目,位置是相对于我的屏幕的。如果我在屏幕上移动应用程序窗口,它们将会有所不同。

下面是我的代码的简化示例(实际上我有多个组件和信号来决定应该加载哪个组件)。

MyType.qml:

Item{
  Button{
    onClicked: {
      loader.sourceComponent = component; // Different positions
    }
  }
  Loader{
    id: loader
    anchors.fill: parent
  }

  Component{
    id: component
    Rectangle{
      Component.onCompleted: {
        var point = mapFromGlobal(0, 0);
        console.log("temp 2: ", point.x, point.y);
      }
    }
  }

  Component.onCompleted: {
    //loader.sourceComponent = component; // Same positions
    var point = mapFromGlobal(0, 0);
    console.log("temp 1: ", point.x, point.y);
  }
}
Run Code Online (Sandbox Code Playgroud)

主.qml

ApplicationWindow {
  id: appWindow

  visible: true

  width: 600
  height: 400

  MyType{
    anchors.fill: parent
  }
}
Run Code Online (Sandbox Code Playgroud)

结果输出是

温度 1: 0 0

温度 2:-199 -85

有谁知道为什么位置有时相对于屏幕,有时相对于应用程序窗口?或者知道这种奇怪行为的另一种解释吗?

编辑:

如果我直接在 Component.onCompleted 中加载组件(在示例代码中已注释掉),那么两个输出都是 0 0。不幸的是,这并没有让我更接近解释,除非它与 Loader 元素有关。