The Problem:
I am trying to find a way of adding a font style to text that as written by the user of my PyQt5 text editor program. I don't want to code each font into some kind of menu manually and I am wondering if there is a built-in way for the user to select their font style for their text like this (Notepad font picker):
My code currently looks like this:
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 has a widget called QFontDialog
, and that is perfect for this case, in the following part I show an example of its use:
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)
Note: You must change the following statement:
fontButton.triggered.connect(lambda: self.font_set)
to:
fontButton.triggered.connect(self.font_set)
Screenshot: