gpt4 book ai didi

python - 字体菜单 PyQt5 文本编辑器

转载 作者:行者123 更新时间:2023-12-01 02:33:59 27 4
gpt4 key购买 nike

问题:

我正在尝试找到一种向 PyQt5 文本编辑器程序的用户编写的文本添加字体样式的方法。我不想将每种字体手动编码到某种菜单中,我想知道是否有一种内置方法可供用户为其文本选择字体样式,如下所示(记事本字体选择器):

Notepad fonts

我的代码目前如下所示:

class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'Text Editor'
self.left = 10
self.top = 10
self.width = 1080
self.height = 920

self.widget = QWidget(self)
self.lbl = QLabel(self)

self.text = QTextEdit(self.widget)
self.widget.setLayout(QVBoxLayout())
self.widget.layout().addWidget(self.text)
self.setCentralWidget(self.widget)
self.initUI()



def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

toolBar = self.menuBar()
fileMenu = toolBar.addMenu('File')
editMenu = toolBar.addMenu('Edit')
toolsMenu = toolBar.addMenu('Tools')
helpMenu = toolBar.addMenu('Help')

fontButton = QAction('Configure Editor', self)
fontButton.setShortcut('Ctrl+E')
fontButton.triggered.connect(lambda: self.font_set)
toolsMenu.addAction(fontButton)

self.show()

def font_set(self):
print("Display Fonts")


if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

最佳答案

Qt 有一个名为 QFontDialog 的小部件,非常适合这种情况,在下面的部分中我将展示其使用示例:

def font_set(self):
font, ok = QFontDialog.getFont(self.text.font(), self)
if ok:
#QApplication.setFont(font)
self.text.setFont(font)
print("Display Fonts", font)

注意:您必须更改以下语句:

fontButton.triggered.connect(lambda: self.font_set)

至:

fontButton.triggered.connect(self.font_set)

屏幕截图:

enter image description here

关于python - 字体菜单 PyQt5 文本编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46458776/

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