问题
If I have a simple, self-contained QML application, I can get the absolute screen coordinates of a component by saying
Component.onCompeted: {
var l = myThing.mapToItem(null, 0, 0)
console.log("X: " + l.x + " y: " + l.y)
}
where myThing is the id of any other component in the file. However, if this file gets incorporated into another QML file and the component it defines is reused, I don't get the screen coordinates anymore; I get the local coordinates relative to the component where the statements above are executed.
How can I get the absolute screen coordinates of items?
回答1:
Component.onCompleted: {
var globalCoordinares = myThing.mapToItem(myThing.parent, 0, 0)
console.log("X: " + globalCoordinares.x + " y: " + globalCoordinares.y)
}
where myThing.parent
is your main compontent.
回答2:
Here is a quick and very dirty solution. Note: This has only been lightly tested but so far seems to work. I would not recommend using this in production applications as it's a complete hack and likely to break at some point.
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));
}
}
}
回答3:
Since Qt 5.7, there is Item.mapToGlobal:
Component.onCompleted: {
var globalCoordinates = mapToGlobal(0, 0)
console.log("X: " + globalCoordinates.x + " y: " + globalCoordinates.y)
}
来源:https://stackoverflow.com/questions/21454393/qml-screen-coordinates-of-component