Qt 清除QML锚
我有一个鼠标a,我想从居中开始,然后在按下上/下/左/右键后有一个绝对位置。我的问题是,我不知道如何清除鼠标earea上的锚,以便指定绝对位置:Qt 清除QML锚,qt,position,qml,qt-quick,Qt,Position,Qml,Qt Quick,我有一个鼠标a,我想从居中开始,然后在按下上/下/左/右键后有一个绝对位置。我的问题是,我不知道如何清除鼠标earea上的锚,以便指定绝对位置: import QtQuick 2.0 import QtQuick.Window 2.0 Window { id: screen width: 360 height: 360 visible: true Rectangle { anchors.fill: parent sta
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.archors
设置为undefined
,但得到了一个关于archors
为只读属性的错误。然后我发现了锚点变更,但我找不到移除/清除锚点的方法;将锚定。底部
等设置为未定义
不起作用。根据,将锚定属性设置为未定义
应该起作用。我不太明白为什么AnchorChanges
不允许设置anchors.centerIn
,但您可以在moveMouseArea
函数中解决这个问题:
function moveMouseArea(x, y) {
mouseArea.anchors.centerIn = undefined; // <-- reset anchor before state change
mouseArea.pos.x += x;
mouseArea.pos.y += y;
mouseArea.state = "moved";
mouseAreaPosText.text = 'Mouse area was moved... new pos: '
+ mouseArea.pos.x + ', ' + mouseArea.pos.y;
}
函数moveMouseArea(x,y){
mouseArea.anchors.centerIn=undefined;//感谢大家的帮助。我发现在一个状态中设置undefined是有效的(如果你所说的有效只是指它不会给出错误),但是一旦元素移动到另一个状态,锚就会神奇地(非常令人沮丧地)出现返回。即使在最终状态中设置了所有未定义的锚点,也会发生这种情况。但是,如上所述,在更改状态之前在函数中设置未定义非常有效。在我的情况下,我在onPressed中的mouseArea中设置它
onPressed: {
plotWindow04Frame.anchors.bottom = undefined
plotWindow04Frame.anchors.left = undefined
plotWindow04Frame.state = "inDrag"
}
我发现没有必要在onReleased中提及锚点,只是下一个状态。
发布日期:{
plotWindow04Frame.state=“已删除”
}
另外,我应该提到的是,最终的“删除”状态也没有提到锚,只是不透明度
states: [
State {
name: "inDrag"
PropertyChanges {
target: plotWindow04Frame
opacity: .5
}
},
State {
name: "dropped"
PropertyChanges {
target: plotWindow04Frame
opacity: 1
}
}
]
transitions: Transition {
NumberAnimation { properties: "opacity"; duration:200 }
}
}
(这里的想法是,这些打印窗口在拖动时将变为半透明(不透明度:0.5),但在用户放置时将返回不透明(不透明度:1)
有趣的是,plotwindow“矩形”最初定位在GUI的底部,但一旦用户拿起它们,他们可以将它们放在任何他们喜欢的地方。Docs()说“如果您希望从使用基于锚定的定位更改为绝对定位,您可以通过将其设置为未定义的”来清除锚定值。”。