Home > Blockchain >  QML Create a component dynamically by mouse press and drag it to a new location
QML Create a component dynamically by mouse press and drag it to a new location

Time:06-17

Good day!

There is an element when you click on which a new element is created: main.qml

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

    x: 200
    y: 200

    width: 50
    height: 50
    color: "black"

    MouseArea {
        anchors.fill: parent

        onPressed:
        {
            var pos = mapToItem(black.parent, mouse.x, mouse.y)
            createNew(pos)

        }

        function createNew(pos) {
            var comp = Qt.createComponent("qrc:/src/qml/NewElement.qml");
            if (comp.status !== Component.Ready)
            {
                console.log("Error creating component");
            }


            var link = comp.createObject(black.parent, { x: pos.x, y: pos.y, z:100});

            if (link === null) {
                console.log("Error creating object");
            }

            return link
        }
    }
}
}

There is a new element that can be dragged: New Element.qml

Item {
id: red

width: 30
height: 30

Rectangle
{
    anchors.fill: parent

    color: "red"
}

MouseArea
{
    anchors.fill: parent
    drag.target: red
    drag.axis: Drag.XandYAxis
}

}

Аfter creating the element, you need to click on the element again to drag it. Question: How to make it so that after creating an element, it can be immediately dragged (with the mouse button pressed)

CodePudding user response:

You can use Drag.* attached properties, something like this:

Rectangle {
    id: container
    anchors.fill: parent
    color: "orange"

    Component {
        id: itemComponent
        Rectangle {
            width: 50
            height: 50
            border.color: "grey"
            radius: 5
            color: "lightblue"
        }
    }

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        onPressed: (mouse)=> {
                       addItem(mouse.x, mouse.y);
                   }
        onReleased: {
            Drag.active = false;
        }

        function addItem(x, y)
        {
            var obj = itemComponent.createObject(container, { x: x - 25, y: y - 25 });
            mouseArea.drag.target = obj;
            Drag.active = true;
        }
    }
}
  • Related