jvanase
jvanase

Reputation: 58

QML/QtQuick2 Anchor Item to static location on a scaled image

What I am attempting to do is anchor an Item over a particular place over an Image. The Image needs to use Image.PreserveAspectFit for the fillMode. The problem I am having is that the height/width/paintedWidth/paintedHeight of the Image are for the entire image "canvas" (I'm not sure what it's actually called), not the drawn part of the image itself. So I can't anchor to the actual image.

See code below for an example I tried with anchors (red rectangle) and with a child rectangle and x,y coordinates (green rectangle).

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true

height: 400
width: 400

Image {
    id: image
    anchors.fill: parent
    fillMode: Image.PreserveAspectFit
    source: "image.jpg"

    Rectangle {
        id: bottomRight
        width: 40
        height: 40
        color: "green"
        x: parent.width * 0.75
        y: parent.height * 0.75
    }
}

Rectangle {
    id: topLeft
    width: 40
    height: 40
    color: "red"

    anchors.top: image.top
    anchors.left: image.left
    anchors.topMargin: image.height * 0.25
    anchors.leftMargin: image.width * 0.25
    }
}

When you change the size of the window the placement of the rectangles is not in the same place over the image. I'd post some screenshots but I don't have enough reputation yet!

I poked around through the widget tree using the debugger but I can't seem to find any properties that provide the information about the scaling that I could use to calculate placement of the rectangles.

Update I used the following functions to calculate the margins since I will be using potentially lots of these overlays.

function horMargin(val)
{
    return ((image.width - image.paintedWidth)/2  + image.paintedWidth * val)
}

function verMargin(val)
{
    return ((image.height - image.paintedHeight)/2 + image.paintedHeight * val)
}

Upvotes: 1

Views: 960

Answers (1)

Mitch
Mitch

Reputation: 24396

Did you try to use paintedWidth and paintedHeight? :)

This will give you a rectangle that fills the painted image:

import QtQuick 2.3
import QtQuick.Window 2.2

Window {
    visible: true

    height: 400
    width: 400

    Image {
        id: image
        anchors.fill: parent
        fillMode: Image.PreserveAspectFit
        source: "image.jpg"
    }

    Rectangle {
        x: (image.width - image.paintedWidth) / 2
        y: (image.height - image.paintedHeight) / 2
        width: image.paintedWidth
        height: image.paintedHeight
        color: "transparent"
        border.color: "darkorange"
        border.width: 2
    }
}

From there, you can work out how to apply the margins that you need.

Upvotes: 0

Related Questions