我有一個MouseArea,我想從中心開始,然後在按下上/下/左/右鍵時有絕對位置。我的問題是,我不知道如何清除在鼠標區域的錨,這樣我可以指定一個絕對位置:清除QML定位點
import QtQuick 2.0
import QtQuick.Window 2.0
Window {
id: screen
width: 360
height: 360
visible: true
Rectangle {
anchors.fill: parent
states: [
State {
name: "moved"
AnchorChanges {
target: mouseArea
anchors.bottom: undefined
anchors.left: undefined
anchors.right: undefined
anchors.top: undefined
}
}
]
MouseArea {
id: mouseArea
anchors.centerIn: parent
width: 250
height: 250
focus: true
onClicked: console.log("clicked!")
onPositionChanged: console.log("position changed!")
function moveMouseArea(x, y) {
mouseArea.x += x;
mouseArea.y += y;
mouseArea.state = "moved";
mouseAreaPosText.text = 'Mouse area was moved... new pos: '
+ mouseArea.x + ', ' + mouseArea.y;
}
Keys.onPressed: {
if (event.key === Qt.Key_Up)
moveMouseArea(0, -1);
if (event.key === Qt.Key_Down)
moveMouseArea(0, 1);
if (event.key === Qt.Key_Left)
moveMouseArea(-1, 0);
if (event.key === Qt.Key_Right)
moveMouseArea(1, 0);
}
Rectangle {
anchors.fill: parent
border.width: 2
border.color: "black"
color: "transparent"
}
Text {
id: mouseAreaPosText
anchors.centerIn: parent
}
}
}
}
起初我只是想設置mouseArea.anchors
到undefined
,但得到一個錯誤約anchors
是一個只讀屬性。然後我發現了AnchorChanges,但是我找不到一種方法去除/清除錨點;設置anchors.bottom
等到undefined
不起作用。
Docs(http://qt-project.org/doc/qt-4.8/qml-anchor-layout.html)說:「如果您希望從使用基於錨點的位置更改爲絕對位置,您可以清除錨點值通過設置爲'undefined'「。 – sergk