1. 程式人生 > >Qt使用字型圖示fontawesome

Qt使用字型圖示fontawesome

為了使用簡單,需要先寫一個單件類,標頭檔案的程式碼如下:

其中靜態方法Instance保證IconHelper的例項全域性唯一

(注意建構函式已經私有化了)

#ifndefICONHELPER_H
#defineICONHELPER_H

#include<QObject>
#include<QMutex>
#include<QMutexLocker>
#include<QtGui>
#include<QtWidgets>
#include<qfont.h>

classIconHelper:publicQObject
{
Q_OBJECT
private:
explicitIconHelper(QObject*parent=0);
QFonticonFont;
staticIconHelper*_instance;
public:
staticIconHelper*Instance()
{
staticQMutexmutex;
if(!_instance)
{
QMutexLockerlocker(&mutex);
if(!_instance)
{
_instance=newIconHelper;
}
}
return_instance;
}
voidSetIcon(QLabel*ctl,QCharc,intsize=10);
voidSetIcon(QPushButton*ctl,QCharc,intsize=10);

signals:

publicslots:

};

#endif//ICONHELPER_H

下面來看一下CPP檔案的程式碼

應用程式所在目錄下建立res目錄,並放置字型檔案/res/fontawesome-webfont.ttf

然後載入到全域性字型中

#include"IconHelper.h"

IconHelper*IconHelper::_instance=0;
IconHelper::IconHelper(QObject*):
QObject(qApp)
{
intfontId=QFontDatabase::addApplicationFont(qApp->applicationDirPath()+"/res/fontawesome-webfont.ttf");
QStringfontName=QFontDatabase::applicationFontFamilies(fontId).at(0);
iconFont=QFont(fontName);
}

voidIconHelper::SetIcon(QLabel*ctl,QCharc,intsize)
{
iconFont.setPointSize(size);
ctl->setFont(iconFont);
ctl->setText(c);
}

voidIconHelper::SetIcon(QPushButton*ctl,QCharc,intsize)
{
iconFont.setPointSize(size);
ctl->setFont(iconFont);
ctl->setText(c);
}

只要這樣呼叫即可:如果你想讓一個QLabel或者QPushButton控制元件顯示一個圖示的話

IconHelper::Instance()->SetIcon(ui->LeftBtn,QChar(0xf177),12);
IconHelper::Instance()->SetIcon(ui->RightBtn,QChar(0xf178),12);

注意,這裡的16進位制的資料是從fontawesome官網上得來的

====================================