QML —— 矩形随鼠标移动或固定位置(附完整源码)

效果

源码
import QtQuick 2.12
import QtQuick.Window 2.12

Window
{
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Text
    {
        id: nameText
        anchors.centerIn: parent
        text: qsTr("text")
        color: "red"
    }

    Rectangle
    {
        id: nameRectangle
        border.color: "yellow"
        border.width: 2
        color: "pink"
        gradient: Gradient
        {
            GradientStop{position: 0.0;color: "#c00a10"}
            GradientStop{position: 1.0;color: "blue"}
        }
        radius: width*0.2
        anchors.right: nameText.left
        anchors.rightMargin: 10
        anchors.verticalCenter: nameText.verticalCenter
        width: 100
        height: 100

        // 动画行为
        Behavior on x{PropertyAnimation{duration: 100}}
        Behavior on y{PropertyAnimation{duration: 100}}

        // 锚点有效性。锚点有效时无法对矩形移动
        property var moveFlag : false;
        function xxx()
        {
            moveFlag = !moveFlag
            if(moveFlag)
            {
                anchors.right = undefined
                anchors.verticalCenter = undefined
            }
            else
            {
                anchors.right = nameText.left
                anchors.rightMargin = 10
                anchors.verticalCenter = nameText.verticalCenter
            }
        }
    }

    MouseArea
    {
        anchors.fill: parent
        enabled: true
        hoverEnabled:true


        onClicked:{nameRectangle.xxx();moveRect()}

        onPositionChanged:{moveRect()}

        function moveRect()
        {
            nameRectangle.x = mouseX-(nameRectangle.width/2)
            nameRectangle.y = mouseY-(nameRectangle.height/2)
            console.log(mouseX,mouseY)
        }
    }
}

关注

笔者 - jxd

你可能感兴趣的:(QML,Qt,QML)