gpt4 book ai didi

python - 如何使用QFontDialog预览非系统字体

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:43 24 4
gpt4 key购买 nike

我想在安装外部字体之前使用 QFontDialog 小部件来预览它们。但是,默认情况下,QFontDialog 显然只列出已安装的系统字体。

  • 有没有办法为 QFontDialog 指定自定义字体文件夹?
  • 如果没有,是否还有其他更适合用作字体预览器的小部件?

最佳答案

您无法指定自定义字体文件夹,但可以使用QFontDatabase添加单独的字体。类(class)。因此,您需要做的就是迭代给定文件夹中的文件并添加其中包含的任何字体文件。该文档指出了这些限制:

Currently only TrueType fonts, TrueType font collections, and OpenType fonts are supported.

Note: Adding application fonts on Unix/X11 platforms without fontconfig is currently not supported.

添加所有有效的字体文件后,它们将立即显示在字体对话框中。这是一个简单的演示(仅在 Linux 上测试):

import sys, os, glob
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.button1 = QtWidgets.QPushButton('Open Font Folder')
self.button1.clicked.connect(self.handleButton1)
self.button2 = QtWidgets.QPushButton('Show Font Dialog')
self.button2.clicked.connect(self.handleButton2)
self.fontList = QtWidgets.QListWidget()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.fontList)
layout.addWidget(self.button1)
layout.addWidget(self.button2)

def handleButton1(self):
path = QtWidgets.QFileDialog.getExistingDirectory(self)
if path:
fonts = set()
self.fontList.clear()
db = QtGui.QFontDatabase()
db.removeAllApplicationFonts()
for filename in glob.glob(os.path.join(path, '*.ttf')):
fontid = db.addApplicationFont(os.path.join(path, filename))
if fontid >= 0:
fonts.update(db.applicationFontFamilies(fontid))
self.fontList.addItems(sorted(fonts))
self.fontList.setCurrentRow(0)

def handleButton2(self):
font = QtGui.QFont()
item = self.fontList.currentItem()
if item is not None:
font.setFamily(item.text())
QtWidgets.QFontDialog.getFont(font, self)

if __name__ == '__main__':

app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 200, 200)
window.show()
sys.exit(app.exec_())

关于python - 如何使用QFontDialog预览非系统字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48839658/

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