Important: Please read the Qt Code of Conduct -

Center an element in a Flickable

  • I want to be able to center an element in a Flickable (and move it around later on and zoom in/zoom out)
    My first attempt was

        Flickable {
            id: flickable
            width: 640
            height: 480
            Rectangle {
                id: rect
                anchors.centerIn: parent
                width: 200
                height: 480
                color: "red"

    which positions the rectangle in the center of the Flickable. However, I can't drag it around

    My next attempt was to add

            contentHeight: rect.height
            contentWidth: rect.width

    Now I can drag around the rectangle but it isn't positioned in the middle anymore
    Finally, I tried to center the rectangle manually by adding

            contentX : (rect.width-flickable.width)/2
            contentY : (rect.height-flickable.height)/2

    This results in a centered Rectangle which I can drag. However, after a small drag, the Rectangle is moved again to contentX=0.

    Can someone explain this? Suggest a fix?

  • What about to wrap Rectangle with Item and place it in center of item with anchors, and then set content size for your Flickable?

  • This works indeed quite nicely for this stripped down example. I'll check whether this also translates to my 'real' problem (where zooming comes into play)

Log in to reply