gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:31 25 4
gpt4 key购买 nike

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

关于python - 在 PyQt 应用程序中加载 FontAwesome,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35129052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com