在PyQt应用程序中加载FontAwesome

2024-04-23 14:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试在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()

Tags: selfid应用程序dbdefsyswindow图标
1条回答
网友
1楼 · 发布于 2024-04-23 14:22:07

好吧,我要把我的解决方案,以防将来有人需要它。有一个名为Qtawesome的pypi包可以让您轻松地加载字体。在

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

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()

相关问题 更多 >