How to transfer drag.active between objects?
-
Hi, for context
-
I have a grid full of "gateIcon" objects
-
I want to be able to click on these objects and drag them around ( if they are dropped in the right position, they stay in that position and a new gateicon component is dynamically created)
-
My initial problem was that I couldn't get the gateicons to be created in the same place they were originally which was obviously undesirable
-
Now, I have changed my approach:
-
Instead of moving the actual gateIcon object, I want to have a 'floatingIcon' object created in the exact same position (when gateIcon.onClicked() is called) and then move the floatingIcon (an Image object with a png) around, this seems like a better approach to me (?)
The issue I am having is that I cannot 'transfer' the drag property from the gateIcon to the floatingIcon. The floatingIcon is created just fine but I have to click twice to move it around which is not really what I want. How can I make it so that in one click I can press the gateIcon, create the floatingIcon and have the floatingIcon follow my mouse (drag it).
Here is the relevant parts of my code: (I have deleted all the irrelevant bits for clarity)
GateIcon.qmlimport QtQuick.Controls 2.15 import Components Rectangle { id: gateIcon signal createFloatingIcon() MouseArea { id: mouseArea onPressed: { if (!isInteractive) return; // drag.target: floatingIcon gateIcon.createFloatingIcon(); } } Image { id: iconImage anchors.centerIn: parent width: parent.width * 0.9 height: parent.height * 0.9 visible: source !== "" fillMode: Image.PreserveAspectFit } }
FloatingIcon.qml
import QtQuick 2.15 Image { id: floatingIcon width: 30 height: 50 source: "" visible: false z: 200 property string gateType property var parentGrid property bool isDragging: false property real startX: 0 property real startY: 0 function startDragging(iconSource, type, initialX, initialY) { console.log("Floating icon initialized at:", initialX, initialY); source = iconSource; gateType = type; startX = initialX; startY = initialY; x = startX; y = startY; visible = true; isDragging = true; mouseArea.forceActiveFocus(); //I need something like this (that actually works) mouseArea.drag.start(); } MouseArea { id: mouseArea anchors.fill: parent drag.target: floatingIcon cursorShape: Qt.ClosedHandCursor onReleased: { floatingIcon.isDragging = false; if (condition) { //handle dropping } else { console.log("Invalid drop: Destroying floating icon", gateType); } floatingIcon.visible = false; } } }
with
onCreateFloatingIcon: { let globalPos = gridIcon.mapToItem(root.contentItem, 0, 0); floatingGateIcon.startDragging(iconSource, gateType, globalPos.x, globalPos.y); }
in main.qml
Thanks in advance for the help!
-