Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block a QML item from getting panned out or its parent's boundaries

Tags:

qt

qml

qtquick2

I have the following code which allows panning of an image on an application window

Code:

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

ApplicationWindow {
    id: app
    visible: true
    title: qsTr("Test panning an Image")

    width: 700
    height: 700

    Image {
        id: my_image_item
        source: "http://doc.qt.io/qt-5/images/declarative-qtlogo.png"
        MouseArea{
            anchors.fill: parent
            drag.target: my_image_item
            drag.axis: Drag.XAndYAxis
        }
    }
}

Objective:
I want to block the image from getting dragged/panned outside its parent.

Basically I do not want to allow my_image_item to be moved out to a position where :

  • my_image_item's right edge is placed leftwards of its parent's left edge,
  • my_image_item's left edge is placed rightwards of its parent's right edge
  • my_image_item's top edge is placed downwards of its parent's bottom edge
  • my_image_item's bottom edge is placed upwards of its parent's top edge

Primary Question:
How can I limit the movement of my_image_item only within the edges of its parent while user is dragging my_image_item?

Secondary question: (if answered then great):
The item that limits my_image_item's movement needs to be strictly its parent? Or it could be another item which is not its parent as well ? (at least one that shares a common QML parent)

like image 455
TheWaterProgrammer Avatar asked Sep 05 '25 03:09

TheWaterProgrammer


1 Answers

Did you try to use drag.maximumX/drag.minimumX

http://doc.qt.io/qt-5/qml-qtquick-mousearea.html#drag.minimumX-prop

Image {
        id: my_image_item
        source: "http://doc.qt.io/qt-5/images/declarative-qtlogo.png"
        MouseArea{
            anchors.fill: parent
            drag.target: my_image_item
            drag.axis: Drag.XAndYAxis
            drag.minimumX: my_image_item.x
            drag.maximumX: my_image_item.right // my_image_item.x + width ???
            drag.minimumY: my_image_item.y
            drag.maximumY: my_image_item.bottom // my_image_item.y + height ???
        }
    }
like image 106
Paltoquet Avatar answered Sep 08 '25 01:09

Paltoquet