1. 程式人生 > >QFontDatabase::addApplicationFont 一直返回-1問題

QFontDatabase::addApplicationFont 一直返回-1問題

    int fontId = QFontDatabase::addApplicationFont(qApp->applicationDirPath() + "/Styles/fontawesome-webfont.ttf");
    QString fontName = QFontDatabase::applicationFontFamilies(fontId).at(0);
    iconFont = QFont(fontName);

       在Linux平臺測試發現程式異常退出,果斷進入除錯模式檢視堆疊資訊。問題出在applicationFontFamilies的at(0)索引越界。

       打斷點發現QFontDatabase::addApplicationFont返回-1,導致程式異常。程式碼在別的虛擬機器上可以成功執行。一開始以為路徑沒有獲取成功,列印 qApp->applicationDirPath(),路徑問題。

按下F1檢視"addApplicationFont"方法幫助文件。

       Loads the font from the file specified by fileName and makes it available to the application. An ID is returned that can be used to remove the font again with removeApplicationFont() or to retrieve the list of family names contained in the font.
The function returns -1 if the font could not be loaded.
Currently only TrueType fonts, TrueType font collections, and OpenType fonts are supported.


Note: Adding application fonts on Unix/X11 platforms without fontconfig is currently not supported.
Note: On Symbian, the font family names get truncated to a length of 20 characters.

    原來Qt幫助文件已經說明了,新增外部字型需要fontconfig 支援。

     果斷百度………………

    需要在Qt庫 configure階段加入 -fontconfig,開啟字型配置(預設是關閉的)。

    首先安裝編譯支援庫 :

        sudo apt-get install libfontconfig1-dev

    開啟QT原始檔,接著:

        ./configure - fontconfig

        sudo make && make install