我希望在我的Qt应用程序中使用fontawesome(http://fontawesome.io/icons)中的一些图标,我已将fontawesome-webfont.ttf文件解压缩到usr / share / fonts.I尝试在线搜索但找不到任何此类示例。是我编写的用于从资源中提取图像的示例代码(不是所需的)以及访问Qfont库本身中存在的一些Qfonts。(例如下面示例中的courier new)。
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QPixmap>
#include <QLabel>
#include <QHBoxLayout>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
centralWidget = new QWidget(this);
gridLayout = new QGridLayout( centralWidget );
mylabel = new QLabel();
mylabel2= new QLabel();
font = new QFont("courier");
addresspic = new QPixmap(":/new/prefix1/address.png");
*addresspic=addresspic->scaled(50,50,Qt::KeepAspectRatio, Qt::FastTransformation);
mylabel->setPixmap(*addresspic);
mylabel2->setTextFormat(Qt::RichText);
mylabel2->setGeometry(QRect(QPoint(100,100),QSize(150, 150)));
mylabel2->setText(" ADDRESS ICON ");
gridLayout->addWidget(mylabel2);
gridLayout->addWidget(mylabel);
font->setItalic(true);
font->setPixelSize(20);
mylabel2->setFont(*font);
// gridLayout->setVerticalSpacing(1);
// gridLayout->setHorizontalSpacing(1);
this->setCentralWidget(centralWidget);
}
MainWindow::~MainWindow()
{
delete ui;
}
再次感谢
从https://github.com/dridk/QFontIcon下载并将qfonticon.h
和qfonticon.cpp
文件添加到您的项目中,然后使用以下代码创建图标:
QFontIcon::addFont("/path/your/fonts/{your font}.ttf");
QIcon icon = QFontIcon::icon(0xf2b9);
{your widget}->setIcon(icon);
例:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include "qfonticon.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget *centralWidget;
QGridLayout *gridLayout;
centralWidget = new QWidget(this);
gridLayout = new QGridLayout( centralWidget );
QFontIcon::addFont("/usr/share/fonts/fontawesome-webfont.ttf");
for(int i = 0; i < 15; i++){
QIcon icon = QFontIcon::icon(0xf2b9+i);
QPushButton *b = new QPushButton();
b->setIcon(icon);
gridLayout->addWidget(b);
}
this->setCentralWidget(centralWidget);
}
MainWindow::~MainWindow()
{
delete ui;
}
更多信息:https://github.com/dridk/QFontIcon
我用Qt 5.7和Qtcreator 4.2测试了它
尝试使用明确加载字体...
int fid = QFontDatabase::addApplicationFont("/usr/share/fonts/fontawesome-webfont.ttf");
然后,您可以使用...查询字体系列名称。
QFontDatabase::applicationFontFamilies(fid);
在我的情况下,上面的结果是单个姓氏“FontAwesome”。既然如此,你应该能够使用字体......
QFont f("FontAwesome");
注意:上面似乎可以正常工作,但指定字体的点大小不能按预期工作。不确定为什么因为ttf文件似乎包含所请求的字形大小。
编辑1上面构造的QFont
可以像任何其他unicode字体一样使用。所以可以创建一个QLabel
...
QLabel label;
label.setFont(QFont("FontAwesome"));
label.setText("\uf0fe"); /* f0fe is the code point for fa-plus-square */
请注意,@ eyllanesc提供的答案可能是一个更好的方法。我只是为了完整性而添加此编辑。