QML的鼠標事件是通過不可見元素MouseArea來實現,常用的事件有點擊,雙擊,長按等。常用的設置有鼠標作用域設置,鼠標按鍵設置等。下面代碼詳細說明
Rectangle{
id:rec_test
height: 300
width: 300
radius: 5
color: "gray"
anchors.centerIn: parent
Text {//配合鼠標事件操作
id: test
anchors.centerIn: parent
font.pixelSize: 35
color: mous.pressedButtons ===Qt.RightButton ? "red" : "blue"
//pressedButtons爲只讀屬性,值爲枚舉值,代表按下時哪一個按鍵
text: "Mouse"
}
Text {//
id: test_mous
font.pixelSize: 20
color: "blue"
text: "mouseX:" +mous.mouseX + "\nmouseY:" + mous.mouseY
//顯示鼠標點擊區域的座標,爲只讀屬性
}
Text {//
id: test_mouspre
anchors.top: test_mous.bottom
font.pixelSize: 20
color: "blue"
text: "pressed:" +mous.pressed
//顯示鼠標是否被按下,爲只讀屬性,按下時爲true,反之false
}
Text {//
id: test_mouscon
anchors.top: test_mouspre.bottom
font.pixelSize: 20
color: "blue"
text: "ContainsMouse:" +mous.containsMouse
//顯示鼠標是否在作用區域內,爲只讀屬性,注意不開啓懸浮功能的話,只有按下才改變
}
Text {//
id: test_dra
anchors.top: test_mouscon.bottom
font.pixelSize: 20
color: "blue"
text: "drag.active:" +mous.drag.active
//顯示指定拖動目標的活動狀態,是否在被拖動
}
MouseArea{
id:mous
anchors.fill: parent //鼠標的作用區域,也可以用寬與高屬性來設置
enabled: true //是否接受鼠標事件,默認true
//hoverEnabled: true //是否處理懸浮事件,也就是沒有點擊時候的時間,例如onPositionChanged,默認false
preventStealing: true //是否防止鼠標時間被竊取,默認爲false,false的時候可以被竊取。
//acceptedButtons: Qt.RightButton | Qt.LeftButton //設置鼠標的觸發區域,例如左鍵右鍵等,默認左鍵
//acceptedButtons: Qt.MiddleButton //中間滑輪的那個按鍵
//acceptedButtons: Qt.XButton1 | Qt.XButton2//這兩個按鍵應該是鼠標邊邊的按鍵,沒測試,因爲我的鼠標上沒有
drag.target: rec_dra //提供一個拖動目標,拖動目標不能使用錨定位,不會拖動無效
drag.axis: Drag.XandYAxis//Drag.YAxis//Drag.XAxis //選擇拖動方式,顧名思義
drag.minimumX: 0 //拖動區域的最小X座標(相對父對象的座標)
drag.maximumX: parent.width - rec_dra.width //拖動區域的最大X座標
drag.minimumY: 0 //拖動區域的最小Y座標
drag.maximumY: parent.height - rec_dra.height //拖動區域的最大Y座標
drag.filterChildren: true
//下面是點擊等信號處理槽
onCanceled: {console.log("onCanceled");}//鼠標時間取消或者被竊取時觸發。
onClicked: {console.log("onClicked");} // 點擊時觸發
onDoubleClicked: {console.log("onDoubleClicked");} //雙擊觸發
onEntered: {console.log("onEntered");} //進入鼠標區域觸發,懸浮屬性爲false,需點擊才觸發
onExited: {console.log("onExited");} //退出鼠標區域(hoverEnabled得爲true),或者點擊退出的時觸發
onPressAndHold: {console.log("onPressAndHold");} //長按觸發,默認時間800ms
onPressed: {console.log("onPressed");} //按下就能觸發
onReleased: {console.log("onReleased");} //釋放時觸發
onPositionChanged: {console.log("onPositionChanged");} //鼠標位置變化(hoverEnabled得爲true),不然得點擊才變化
Rectangle{ //提供被拖拽
id:rec_dra
height: 50
width: 50
y:200
x:100
// anchors.horizontalCenter: parent.horizontalCenter
// anchors.bottom: parent.bottom
color: "red"
}
}
}