Qt使用字体图标fontawesome
程序员文章站
2022-03-02 10:33:48
...
为了使用简单,需要先写一个单件类,头文件的代码如下:
其中静态方法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);
详见:http://fontawesome.io/cheatsheet/
注意,这里的16进制的数据是从fontawesome官网上得来的
====================================