字体菜单PyQt5文本编辑器
问题描述:
我试图找到添加字体样式的文本的方式,如写我的PyQt5文本编辑器程序的用户。我不希望手动将每种字体编码到某种菜单中,而且我想知道是否有内置方式供用户选择其文本的字体样式(记事本字体选择器):
我的代码目前看起来是这样的:
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)
截图: