06/08/2017

Qt/QML: Scale Text

Lập trình Qt/QML cho di động (mobile) nhất là Android, không ít lần mình phải đối mặt với bài toán làm sao đoạn text có thể lớn nhỏ đủ trong khung đất dành cho nó dù cho font chữ có thay đổi tuỳ theo thiết bị. 
Sau đây là cách làm của mình:
NLCScalableText.qml:
import QtQuick 2.7
Text {
    /**
      * This is scale rate we want the text must follow.
      * incase that we want share the scale rate to other text.
      */
    property real niceScale:1.0;
    /**
      * This is the scale rate we want the text to scale.
      */
    property real wantScale:idNLCTextPrivate.getWantScale();
    id:idNLCText
    QtObject{
        id:idNLCTextPrivate
        function getWantScale(){
            if (idNLCText.width > 0){
                return (idNLCText.paintedWidth/idNLCText.lineCount) > idNLCText.width ? ((idNLCText.width*idNLCText.lineCount) / idNLCText.paintedWidth): 1;
            }else{
                return 1.0;
            }
        }
        function getScale(){
            return Math.min(idNLCText.niceScale, getWantScale());
        }
    }
    scale:idNLCTextPrivate.getScale();
    horizontalAlignment: Text.AlignHCenter
}