QML how to adapt to different devices

Doing embedded and mobile development, different devices, different resolutions need to be able to adapt the UI, this is a very realistic problem. QML as Qt born for the UI, the use of QML must solve the problem of adaptation.

Resolution

Now the same size screen, its resolution is different, in QML using anchors for the relative layout, it is in pixels. Now there is a concept called number of pixels per inch. When the PPI of the device is different, the size of the control is different, which may result in, if the design is on a screen with a small size and low PPI, and the program is put on a device with a large size and high PPI, then the control will look smaller, so it is not desirable to use pixel layout directly in QML.

Screen

Screen provided in QML provides us with device related data, one of the important is DPI (Devices per mm pixel), the device pixels per millimeter, by this we can do the layout in mm as a standard, so that we do not appear, in the high-resolution device, the control become very small on high-resolution devices.

property real dpi: Screen.pixelDensity.toFixed(2)

1

Device a property that takes two decimal points. Then it can be set like this

anchors {top:parent.top; topMargin: 2 * dpi;}

1

This control is 2mm above parent, and it behaves the same regardless of the device, so it behaves the same for the length and width of the control.

When we design the interface, we must design it in one size, then if we change a very big device, then the control is not suitable, then we need to have a little bit of scalability.

Scaling

Screen.height and Screen.width are the length and width of the current display device, but they are pixels, to get the actual size, you need to divide by dpi.

Suppose that we design the length and width of a and b, and we get the length and width of c and d at runtime.

So the layout of the should look like this

anchors {top:parent.top; topMargin: 2 * dpi * (d/b);}

1

Then it is the same for the length and width of the controls, so we realize that the controls and their spacing scales differently with the size of the controls on different devices.