qt – How to handle screen orientation in QML?

Question:

I develop normally focused in a vertical orientation, but when I turn the device's screen to landscape, the elements are undesiredly resized, leaving some smaller than they really should be.

For example:

Rectangle
{
    id: foo
    width: parent.width * 0.8;
    height: parent.height * 0.025;
}

On a 1024 x 600 device, when vertically foo is 25px high, but when horizontally it is 15px, which compromises the reading of possible texts inside the Rectangle .

Is it possible to set a minimum size for when horizontal?
And how best to handle screen orientation issues in QML?

Answer:

You can deduce the screen orientation from the width/height ratio. An example:

Item {
    id: root
    property int isVertical: width/height < 1

    Text {
        text: root.isVertical ? "Vertical" : "Horizontal"
        anchors.centerIn: parent
    }
}

But making use of a conditional like that can make the layout not change fluidly when someone resizes the window (on desktop). If the focus is only on devices with a fixed screen size, then you don't have to worry so much about it.

Anyway, it's best to build the layout to fit the screen size, whatever it is. After all, you can have a vertical that is much smaller than expected and the text will be unreadable anyway. Set a minimum size!

Item {
    id: root

    Rectangle {
        anchors.centerIn: parent
        color: "green"
        width: parent.width * 0.8
        height: Math.max(parent.height / 6, 25)
    }
}

This way any text inside the rectangle will always be readable.

Scroll to Top