How to deal with anchoring while making a QML item Draggable?



  • I have QML which host an image. I need to allow the user to pan the image. Basically be able to drag it around.

    I figured that Drag QML type gives me this capability. It works as well using something like below:

    MyQmlComponent {
        id: myqmlitem
        anchors.top: parent.top
        anchors.horizontalCenter: parent.horizontalCenter
    
        Drag.dragType: Drag.Automatic
    
        MouseArea {
            anchors.fill: parent
            drag.target: myqmlitem
    
            drag {
                axis: Drag.XandYAxis
    
                onActiveChanged: {
                    console.log("Active changed..")
                     
                    anchors.top = undefined
                    anchors.horizontalCenter = undefined
                    // I want to unset the anchors here and reset it back at a later stage. But how?
                }
            }
        }
    }
    

    I figured the anchoring properties are coming in the way of my drag/pan feature. How should I deal with this? Are there any ways to set and unset the anchors? Doing the below doesn't seem to work.

    anchors.top = undefined
    anchors.horizontalCenter = undefined
    

    Basically, I want to unset the anchors when drag is active. And unset it at a later stage. Please suggest if there are other ways to deal with this as well..


  • Moderators

    @Roby-Brundle
    according to the docs assigning undefined to anchors is the correct way to reset them.

    What is the exact behavior in your case?



  • @raven-worx setting it to undefined doesn't help. I have the undefined set already in the code. it doesn't seem to work at all.
    Seems like the anchors i am trying to set and unset do not take affect on myqmlitem ?


  • Moderators

    @Roby-Brundle
    and i ask again (one last time):

    What is the exact behavior in your case?



  • @raven-worx The exact behaviour was that the default anchors which are the following

    anchors.top: parent.top
    anchors.horizontalCenter: parent.horizontalCenter
    

    were not getting unset by doing setting it undefined. That means that myqmlcomponent remained anchored to top and horizontalCenter. if they were really getting unset then I would be able to drag myqmlcomponent to different X and Y coordinates.

    But the good news is that I figured this out. I needed to refer to myqmlcomponent when setting it anchors to undefined. Like below:

    onActiveChanged: {
        myqmlcomponent.anchors.top = undefined
        myqmlcomponent.anchors.horizontalCenter = undefined
    }
    

    Now it works fine to unset or reset the anchors well


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.