How to get the absolute mouse position from the mouse area ? I need to have it to show a popup a the correct position
Item {
Menu {
id: menu
MenuItem {
onTriggered: {
// Need Mouse absolute position
}
}
}
MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: {
menu.popup()
}
}
mapToItem
, mapFromItem
mapToGlobal
, mapFromGlobal
onClicked: {
var positionInPopup = mapToItem(popup, mouse.x, mouse.y)
}
Like hinted by indalive, the preferred method for mapping coordinates is by using mapToItem
, available for any Item. It transforms coordinates (and size) from current Item coordinates system (if not specified otherwise) to another Item coordinates system. And the mapFromItem
counterpart does the reverse, naturally.
From Qt 5.7, you also have mapToGlobal
, which will give you coordinates in the system/screen referential.
MouseArea {
// ...
onPositionChanged: {
var positionInRoot = mapToItem(root, mouse.x, mouse.y)
var positionInWindow = mapToItem(window.contentItem, mouse.x, mouse.y)
var globalPosition = mapToGlobal(mouse.x, mouse.y)
console.log("For root: " + positionInRoot )
console.log("For window: " + positionInWindow)
console.log("For system: " + globalPosition)
}
}
Given the example above, and ...
MouseArea
is close to root
, a bit further from your Window
top left corner... you will see:
For root: QPointF(10, 0)
For window: QPointF(150, 100)
For system: QPointF(1230, 120)
Window
typeWhen converting to/from a Window
(QML type), you need to use its contentItem
property, as mapTo/From only work with Item
s.
You probably found the answer already, but I'll put my solution here for others looking for the same thing.
The below function will find the absolute position of the mouse area. And then you can add mouseX and mouseY accordingly to get mouse position.
Item {
Menu {
id: menu
MenuItem {
onTriggered: {
var absolutePos = getAbsolutePosition(source);
// Need Mouse absolute position
}
}
}
MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: {
menu.popup()
}
}
function getAbsolutePosition(node) {
var returnPos = {};
returnPos.x = 0;
returnPos.y = 0;
if(node !== undefined && node !== null) {
var parentValue = getAbsolutePosition(node.parent);
returnPos.x = parentValue.x + node.x;
returnPos.y = parentValue.y + node.y;
}
return returnPos;
}
}
In this case mouseArea fills his parent (anchors.fill: parent), therefore mouseArea.mouseX and mouseArea.mouseY are absolute mouse position. For relative positions you should use mapFromItem and mapToItem functions http://doc.qt.io/qt-5/qml-qtquick-item.html#mapToItem-method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With