赞
踩
在编写qt界面的过程中,经常会使用到一些图标字体。fontawesome是一个很不错的图标字体库,通过使用fontawesome可以显示很多图标。
fontawesom官网:fontawesome图标字体库
把fontawesome-webfont.ttf加载到资源文件
直接上干货,头文件如下:
- #ifndef ICONHELPER_H
- #define ICONHELPER_H
-
- #include <QObject>
- #include <QFont>
- #include <QFontDatabase>
- #include <QMutex>
- #include <QLabel>
- #include <QPushButton>
- #include<QToolButton>
- #include <QApplication>
-
- class IconHelper : public QObject
- {
- private:
- explicit IconHelper(QObject *parent = 0);
- QFont iconFont;
- static IconHelper* _instance;
-
- public:
- static IconHelper* Instance()
- {
- static QMutex mutex;
- if (!_instance) {
- QMutexLocker locker(&mutex);
- if (!_instance) {
- _instance = new IconHelper;
- }
- }
- return _instance;
- }
-
- void SetIcon(QLabel* lab, QChar c, int size = 10);
- void SetIcon(QPushButton* btn, QChar c, int size = 10);
- void SetIcon(QToolButton* btn, QChar c, int size = 10);
-
- };
-
- #endif // ICONHELPER_H

CPP文件如下:
- #include "iconhelper.h"
-
- IconHelper* IconHelper::_instance = 0;
- IconHelper::IconHelper(QObject*):
- QObject(qApp)
- {
- int fontId = QFontDatabase::addApplicationFont(":/image/fontawesome-webfont.ttf");
- QString fontName = QFontDatabase::applicationFontFamilies(fontId).at(0);
- iconFont = QFont(fontName);
- }
-
- void IconHelper::SetIcon(QLabel* lab, QChar c, int size)
- {
- iconFont.setPointSize(size);
- lab->setFont(iconFont);
- lab->setText(c);
- }
-
- void IconHelper::SetIcon(QPushButton* btn, QChar c, int size)
- {
- iconFont.setPointSize(size);
- btn->setFont(iconFont);
- btn->setText(c);
- }
- void IconHelper::SetIcon(QToolButton* btn, QChar c, int size)
- {
- iconFont.setPointSize(size);
- btn->setFont(iconFont);
- btn->setText(c);
- }

调用
- IconHelper::Instance()->SetIcon(ui->closeBtn, QChar(0xf00d), 10);
- IconHelper::Instance()->SetIcon(ui->maxBtn, QChar(0xf096), 10);
- IconHelper::Instance()->SetIcon(ui->minimumBtn, QChar(0xf068), 10);
运行效果截图:
![]()
fontawesome图标对应字符截图:

下载链接:https://download.csdn.net/download/weixin_41882459/12748864
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。