python logo

pyqt5 font


Python hosting: Host, run, and code Python in the cloud!

PyQt5 comes with a font dialog that you may have seen in a text editor. This is the typical dialog where you can select font, font size, font style and so on. Of course the look and feel depends on the operating system.

To open this dialog import QFontDialog call:

QFontDialog.getFont()

To use it, import QFontDialog from QtWidgets like this:

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFontDialog

Related course:

PyQt5 font dialog

The example below opens a font dialog on a button event, the selected font (font family including size) will be returned as a string.

pyqt-font-dialog Font Dialog using PyQt5

Opening a font dialog is as simple as

def openFontDialog(self):
font, ok = QFontDialog.getFont()
if ok:
print(font.toString())

Then add a pyqt5 button that opens the dialog. To do that, you need a pyqtslot.

A full code example is shown below


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFontDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 font dialog - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

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

button = QPushButton('Open PyQt5 Font Dialog', self)
button.setToolTip('font dialog')
button.move(50,50)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
openFontDialog()

def openFontDialog(self):
font, ok = QFontDialog.getFont()
if ok:
print(font.toString())

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

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

BackNext





Leave a Reply:




The Ubuntourist 2021-07-06T20:06:00.974Z

Two typos in the Fonts Dialog example (https://pythonspot.com/pyqt5-font-dialog/):

On line 31, in on_click() 'openFontDialog(self)' should be 'self.openFontDialog()'.

Line 35-36 in openFontDialog() has the wrong indentation. An additional four spaces is needed at the start of each line.

Frank 2021-07-06T20:06:01.974Z

Thanks, updated the code with the right call and indention.

Ashley 2021-06-17T14:18:30.345Z

These tutorials have been very helpful, however when I run the above I get 'NameError: name 'ok' is not defined'. how can I correct this?

Frank 2021-06-17T14:18:31.345Z

Seems you have a typo