Qt下使用自定义字体

首先看下QFontDatabase类的说明:

The QFontDatabase class provides information about the fonts available in the underlying window system. More...

 

 也就是说QFont使用的是系统字体,而不能是自定义字体!

所以为了使用自定义字体,必须将自定义字体安装(copy)到系统字体文件夹中(如C:\windows\fonts).

/*
 * 名称:modifyFont
 * 参数:const QString
 * 功能:更改本程序所使用的字体
 * 返回:bool
 */
bool Monitor::modifyFont(const QString str)
{
    //安装字体
    QFile file(tr(":/res/%1.ttf").arg(str));
    file.copy(tr("C:/WINDOWS/Fonts/%1.ttf").arg(str));
    QFontDatabase fd;
    QStringList sl  = fd.families();
    if(sl.contains(str))
    {
        QFont font;
        font.setFamily(str);
        setFont(font);
        return true;
    }
    return false;
}

 

 注意:字体文件的名称必须是字体的名称。因为QFontDatabase::families获取的是字体的名称,而不是字体文件的名称.

setFamily也是如此。

存在的问题:QFile::copy无法监控什么时候完成,所以第一次调用该函数的时候会返回false,因为判断QFontDatabase中是否存在目标字体时,改字体尚在复制操作当中.如果有朋友能看到这篇随笔,而且能够帮助我解决此问题,恳请您帮助。

posted @ 2013-03-02 12:22  justwake  阅读(2307)  评论(3编辑  收藏  举报