需求一:点击按钮弹出菜单,并且自定义菜单弹出位置。
mouse.x
和 mouse.y
获取的是相对于 MouseArea
(在这个例子中是 Button
)左上角的局部坐标。如果你想要在鼠标点击位置显示 Menu
,你需要将这个局部坐标转换为相对于应用程序窗口或屏幕的全局坐标。
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15Window {width: 640height: 480visible: truetitle: qsTr("Demo Cloud Music Player")//从全局对象拿到的点是正确的MouseArea{anchors.fill: parenthoverEnabled: trueonClicked: {console.log("mouse = ",mouseX,mouseY,mouse )myMenu.popup(mouseX,mouseY)}}// 创建一个菜单并添加菜单项Menu {id: myMenuMenuItem {text: "Option 1"onTriggered: console.log("Option 1 selected")}MenuItem {text: "Option 2"onTriggered: console.log("Option 2 selected")}MenuItem {text: "Option 3"onTriggered: console.log("Option 3 selected")}}Button{id:myButtonwidth: 100height: 100x:100// 将菜单与按钮关联// menu: myMenubackground:Rectangle{width: 25height: 25color: "red"border.color: "blue"}//方式一:从MouseArea获取到点的位置发现不正确MouseArea{anchors.fill: parenthoverEnabled: trueonClicked: {var globalPos = myButton.mapToGlobal(mouse.x, mouse.y)console.log("MouseArea = ",mouseX,mouseY)console.log("mouse对象 = ",mouse.x,mouse.y,mouse )console.log("globalPos对象 = ",globalPos.x,globalPos.y,globalPos )//方式二//mouse.x获取到的值是对于当前控件来说,需要加上偏移量myMenu.popup(mouse.x+myButton.x, mouse.y)console.log("myMenu对象 = ",myMenu.x,myMenu.y,myMenu )}}//正确方式一:// onClicked: {// console.log("clicked")// // 获取按钮的全局坐标这俄格应该是获取到的是控件坐标// // var globalPos = myButton.mapToItem(null, 0, myButton.height)// // 在按钮下方显示菜单,先让他显示出来获取到坐标在显示一遍进行实现// myMenu.popup() // 默认就会在鼠标的当前位置打开。。。// console.log("x = ",myMenu.x,"y = " ,myMenu.y)// var x = myMenu.x +10// var y = myMenu.y +10// myMenu.popup(x,y)// }Keys.onLeftPressed: {console.log("left")}Keys.onRightPressed:{console.log("right")}}}