Brett
Brett

Reputation: 332

QML: Can I draw a rectangle from its center, not from its corner?

If I want to visualize a point in qml i could do something like this:

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.2
import QtQuick.Layouts 1.0

ApplicationWindow{
    width: 1024
    height: 256
    visible: true

    ColumnLayout {
        anchors.fill: parent

        Rectangle {
            x: 10
            y: 10
            width: 5
            height: 5
            color: "white"
        }
    }
}

However the rectangle will draw drom its upper left corner down. Is there a way to draw the rect that centers at x, y?

Thanks

Upvotes: 3

Views: 1167

Answers (1)

Mitch
Mitch

Reputation: 24416

Not using Rectangle as-is, but you can make your own items. Using the transform property allows x and y to refer to the centre of the rectangle.

MyRectangle.qml:

import QtQuick 2.0

Rectangle {
    id: rect

    transform: Translate {
        x: -rect.width / 2
        y: -rect.height / 2
    }
}

You'd then use it like so:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    width: 200
    height: 200
    visible: true

    MyRectangle {
        x: 50
        y: 50
        width: 50
        height: 50
        color: "darkorange"
    }
}

rectangle example

Upvotes: 2

Related Questions