Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Position change when parent resizes



  • How do I properly change the x, y of an object so that it changes its position when the parent is resized? There is, I will introduce that if I drag the rectangle to the middle, then when the window is resized, it should remain in the middle. (middle for example only, rectangle can be moved freely)

    import QtQuick 2.9
    import QtQuick.Window 2.2
    import QtQuick.Controls 2.3
    
    Window {
        visible: true
        width: 640
        height: 480
    
    onWidthChanged: {
                block.x -= block.previousWidth - width
                block.previousWidth = width
            }
    
    onHeightChanged: {
                block.y -= block.previousHeight - height
                block.previousHeight = height
            }
    
        Rectangle {
            id: block
            color: "red"
            width: 50
            height:50
            x: 100
            y: 50
    
           property int previousWidth: 0
           property int previousHeight:0
    
           Component.onCompleted: { 
              previousWidth = parent.width
              previousHeight  = parent.height
    }
    
            MouseArea {
                anchors.fill: parent
                drag.target: block
            }
        }
    }
    

Log in to reply