qt – 清除QML锚点

前端之家收集整理的这篇文章主要介绍了qt – 清除QML锚点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个MouseArea,我想要从中心开始,然后按一下上/下/左/右键的绝对位置。我的问题是我不知道如何清除MouseArea上的锚点,以便我可以指定绝对位置:
import QtQuick 1.1

Rectangle {
    id: screen
    width: 360
    height: 360

    function moveMouseArea(x,y) {
        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;
    }

    Item {
        id: keyHandler
        focus: true
        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);
            }
        }
    }

    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
        onClicked: {
            console.log("clicked!");
        }
        onPositionChanged: {
            console.log("position changed!");
        }

        Rectangle {
            anchors.fill: parent
            border.width: 2
            border.color: "black"
            color: "transparent"
        }

        Text {
            id: mouseAreaPosText
            anchors.centerIn: parent
        }
    }
}

起初我刚刚尝试将mouseArea.anchors设置为undefined,但是有一个关于anchor是一个只读属性错误。然后我发现了AnchorChanges,但是我找不到删除/清除锚点的方法;将anchorors.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;
}
原文链接:https://www.f2er.com/css/218222.html

猜你在找的CSS相关文章