Skip to main content
 首页 » 编程设计

python之在 PyQt 应用程序中加载 FontAwesome

2024年10月24日9me-sa

我一直在尝试在我的 PyQt 应用程序中使用 FontAwesome 中的图标。我已经下载了 .ttf 文件,并使用 addApplicationFont 方法将字体加载到我的应用程序中。我有一个 QToolButton,我想为其设置 AwesomeFont 的图标。我无法弄清楚如何从数据库中选择一个图标。附上代码供引用:

import sys 
 
from PyQt4 import QtGui, QtCore 
 
class Window(QtGui.QMainWindow): 
    css = """ 
        QToolButton{{ 
            border: None; 
        }} 
    """ 
 
    def __init__(self): 
        super(Window, self).__init__() 
 
        font_id = QtGui.QFontDatabase.addApplicationFont("fontawesome-webfont.ttf") 
 
        if font_id is not -1: 
            font_db = QtGui.QFontDatabase() 
            self.font_styles = font_db.styles('FontAwesome') 
            self.font_families = QtGui.QFontDatabase.applicationFontFamilies(font_id) 
            for font_family in self.font_families: 
                self.font = font_db.font(font_family, self.font_styles.first(), 24) 
        self.home() 
 
    def home(self): 
        self.setStyleSheet(self.css.format()) 
 
        btn = QtGui.QToolButton(self) 
        btn.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) 
        btn.setFont(self.font) 
        btn.setText('.....') 
        btn.clicked.connect(QtCore.QCoreApplication.instance().quit) 
 
        self.show() 
 
def run(): 
    app = QtGui.QApplication(sys.argv) 
    GUI = Window() 
    sys.exit(app.exec_()) 
 
run() 

请您参考如下方法:

好吧,我将放入我的解决方案,以防将来有人需要它。有一个名为 Qtawesome 的 pypi 包,可让您通过几个简单的步骤加载字体。

但是如果有人不想使用第 3 方包,那么我已经修改了上面的代码,其中包含所有缺失的语句。

import sys 
from six import unichr 
 
from PyQt4 import QtGui, QtCore 
 
class Window(QtGui.QMainWindow): 
    css = """ 
        QToolButton{{ 
            border: None; 
        }} 
    """ 
 
    def __init__(self): 
        super(Window, self).__init__() 
 
        font_id = QtGui.QFontDatabase.addApplicationFont("fontawesome-webfont.ttf") 
 
        if font_id is not -1: 
            font_db = QtGui.QFontDatabase() 
            self.font_styles = font_db.styles('FontAwesome') 
            self.font_families = QtGui.QFontDatabase.applicationFontFamilies(font_id) 
            for font_family in self.font_families: 
                self.font = font_db.font(font_family, self.font_styles.first(), 24) 
        self.home() 
 
    def home(self): 
        self.setStyleSheet(self.css.format()) 
 
        btn = QtGui.QToolButton(self) 
        btn.setToolButtonStyle(QtCore.Qt.ToolButtonIconOnly) 
        btn.setFont(self.font) 
        btn.setText(unichr(int('e025', 16))) 
        btn.clicked.connect(QtCore.QCoreApplication.instance().quit) 
 
        self.show() 
 
def run(): 
    app = QtGui.QApplication(sys.argv) 
    GUI = Window() 
    sys.exit(app.exec_()) 
 
run()