2010-06-21

Define Font in QML

Due to the bug QTBUG-11611, you should avoid to use relative path to define font file in qml code. Otherwise if you load the qml file by QDeclarativeView in c++ code, you will get a error message like "Cannot load font: QUrl( "file:///D:/work/projects/qt/fonts-build/fonts/tarzenau-ocr-a.ttf" )".


//bad example
FontLoader { id: localFont; source: "fonts/tarzenau-ocr-a.ttf" }
Text {
   text: myText; color: "lightsteelblue"
   font.family: localFont.name; font.pointSize: 42
}

//good example
//but you need to copy tarzenau-ocr-a.ttf to ~/.fonts 
//or $WINDOWS/Fonts in windows
Text {
   text: myText; color: "lightsteelblue"
   font.family: "tarzenau-ocr-a"; font.pointSize: 42
}
You can reuse this script to install your font to ~/.font.
#!/bin/sh
# This script install the ttf files in source to ~./fonts

SOURCEDIR=../fonts
TARGETDIR=~/.fonts

#=====================
# check font dir
#=====================

if [ ! -d $TARGETDIR ]; then
   echo "$TARGETDIR does not exist! => create it."
   mkdir $TARGETDIR
fi

if [ ! -d $TARGETDIR ]; then
   echo "Error: Fail to create $TARGETDIR!"
   exit 1
fi

#=====================
# check source font dir
#=====================
if [ ! -d $SOURCEDIR ]; then
    echo "Error: source font dir '$SOURCEDIR' does not exist!"
    exit 1
fi

#================
# copy start
#================

cp -f $SOURCEDIR/*.ttf $TARGETDIR/
echo "ttf files in '$SOURCEDIR' have been copy to '$TARGETDIR'"
echo "Success."

No comments:

Post a Comment