QT beautify the use of font icons

Prepare font icon resources

Fontawesome download address
Unzip the file and get the following
Insert picture description here

Establish QT project

Use qtcreator to create mainwindow project

Project adds font icon resource files

In .proincreasing the file reads as follows:

RESOURCES += \
    resource/resource.qrc

Then create in the project directory

#建立resource目录
mkdir -p resource
mkdir -p resource/ico_ttf
#建立qrc文件
touch resource/resource.qrc

Edit resource.qrcfile

<RCC>
    <qresource prefix="/resource_file"/>
    <qresource prefix="/">
        <file>ico_ttf/fontawesome-webfont.ttf</file>
    </qresource>
</RCC>

Copy from the downloaded fontawesome decompression directory fontawesome-webfont.ttfto the ico_ttfdirectory

Create a button control

Open the UI design tool and drag a PushButton to the interface

In the instantiation in mainwindow.cpp

/*装载图形字体*/
QFont iconFont;
QFontDatabase fontDb;
if(!fontDb.families().contains("FontAwesome"))
{
    
    
    int fontId = fontDb.addApplicationFont(":/ico_ttf/fontawesome-webfont.ttf");
    QStringList fontName = fontDb.applicationFontFamilies(fontId);
    if(fontName.count() == 0)
    {
    
    
        qDebug() << "load fontawesome-webfont.ttf error";
    }
}
if(fontDb.families().contains("FontAwesome"))
{
    
    
    iconFont = QFont("FontAwesome");
    iconFont.setHintingPreference(QFont::PreferNoHinting);
}
iconFont.setPixelSize(14);

Set button font
Find the font you want to set
Insert picture description here
Copy name fa-file-textto font-awesome.csssearch
Insert picture description here

QString ico_text = QString("%1%2").arg(QChar(0xf15c)).arg(" 文件");
ui->pushButton->setFont(iconFont);
ui->pushButton->setText(ico_text);

running result

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42892101/article/details/111912016