DomTomCat
DomTomCat

Reputation: 8569

Dynamically change the transformation of a QML element

It took quite some time for me to figure out a problem I had about rotating a QML object, so I decided to share this.

The question: How can I dynamically update the rotation of a QML element (like image). I know I can set, e.g. the rotation using a transformation (in the example of a MapQuickItem):

MapQuickItem
{
    sourceItem: Image
    {
        id: image
        anchors.centerIn: parent
        source: "image.png"
        sourceSize.width:  Screen.devicePixelRatio * 256
        sourceSize.height: Screen.devicePixelRatio * 256
        transform: Rotation { 
            origin { x: image.sourceSize.width/2; 
                     y: image.sourceSize.height/2; 
                     z: 0} 
            angle: 0
        }
    }
}

However, how can I update the angle (or other parts of the transform) dynamically?

Upvotes: 0

Views: 2760

Answers (2)

augre
augre

Reputation: 2051

A cleaner way to do it would be using a property or an alias:

MapQuickItem
{
    sourceItem: Image
    {
        id: image

        property alias rotationAngle: rotation.angle

        anchors.centerIn: parent
        source: "image.png"
        sourceSize.width:  Screen.devicePixelRatio * 256
        sourceSize.height: Screen.devicePixelRatio * 256
        transform: Rotation { 
            id: rotation
            origin { x: image.sourceSize.width/2; 
                     y: image.sourceSize.height/2; 
                     z: 0} 
            angle: 0
        }
    }
}

with:

function updatePositionAndRotation(angleDeg)
{
    image.rotationAngle = angleDeg
}

Upvotes: 3

DomTomCat
DomTomCat

Reputation: 8569

The key information was that transform is actually a list of transformations.

So one possible solution to the above question is a function like this (e.g. changing the rotation):

function updateRotation(angleDeg)
{
    image.transform[0].angle = angleDeg;
}

Upvotes: 1

Related Questions