qt - 清除 QML anchor

标签 qt position qml qt-quick

我有一个 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/

相关文章:

python - 使用 concurrent.futures.ThreadPoolExecutor 时用户界面卡住

c# - 如何在 xaml WPF 中的堆栈面板或网格上设置绝对位置

qt - 如何将 QML View 嵌入 native 窗口

animation - QML 中的 anchor 动画

qt - 在不使用状态的情况下多次播放 QML 动画

连接到 Qt 信号的 Python lambda 函数在不同线程中创建时不会运行

qt - 我如何开始使用 QtLinguist 来翻译我的 QtCreator 项目?

c++ - 在 Qt for Web Assembly 上访问本地用户文件

r - 如何在R中的ggplot2中躲避点

css - 无法将两个 div 直接放在彼此之上