gpt4 book ai didi

qt - 清除 QML anchor

转载 作者:行者123 更新时间:2023-12-02 03:37:03 26 4
gpt4 key购买 nike

我有一个 MouseArea,我想从中心开始,然后在按下上/下/左/右键后获得绝对位置。我的问题是我不知道如何清除 MouseArea 上的 anchor 以便我可以指定绝对位置:

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,但我找不到删除/清除 anchor 的方法;将 anchors.bottom 等设置为 undefined 不起作用。

最佳答案

根据docs ,将 anchor 属性设置为 undefined 应该可以。我不太明白为什么 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;
}

关于qt - 清除 QML anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10869785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com