How to deal with screen orientation in QML?

Posted on

Question :

I develop normally focused on vertical orientation, but when I turn the device screen to horizontal, the elements are resized unwanted, leaving some smaller than they really should be.

For example:

    id: foo
    width: parent.width * 0.8;
    height: parent.height * 0.025;

In a 1024 x 600 device, when vertically foo is 25px tall, but when horizontally it gets 15px, which compromises the reading of possible texts within Rectangle .

Can I set a minimum size when I’m horizontal?
And what is the best way to handle screen orientation issues in QML?


Answer :

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

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

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

But making use of such a conditional can make the layout not change fluidly when someone resizes the window (desktop). If the focus is only fixed-size devices, you do not have to worry about that much.

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 in the same way. 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)

So any text within the rectangle will always be readable.


Leave a Reply

Your email address will not be published. Required fields are marked *