PyQt - QFontDialog Widget



Another commonly used dialog, a font selector widget is the visual appearance of QDialog class. Result of this dialog is a Qfont object, which can be consumed by the parent window.The class contains a static method getFont(). It displays the font selector dialog. setCurrentFont() method sets the default Font of the dialog.

QFontDialog provides a convenient way for users to choose fonts by presenting a dialog with various font options. Developers can utilize this widget to enhance the user experience and customize text appearance within their applications.

Methods of QFontDialog Widget

Method Description
getFont() Opens a font dialog and returns the selected font along with a boolean indicating if the user accepted the selection.
setFont(font) Sets the initial font displayed in the dialog.
setOption(option, on=True) Sets or clears the specified option.
setFontDialogOptions(options) Sets the options that control the appearance and behavior of the font dialog.
options() Returns the current options set for the font dialog.

Basic Usage of QFontDialog

To use QFontDialog in a PyQt6 application, first, import the necessary modules. Then, create a button to trigger the font dialog and connect it to a function.

In the below example, when we click the button it opens the font dialog which allows the user to choose a font. When you select a font then its details is printed to the console.

from PyQt6.QtWidgets import QApplication, QFontDialog, QPushButton

def open_font_dialog():
   font, ok = QFontDialog.getFont()
   if ok:
      print("Selected Font:", font.toString())

app = QApplication([])
button = QPushButton("Select Font")
button.clicked.connect(open_font_dialog)
button.show()
app.exec()

Output

The above code produces the following output −

pyqt qfontdialog basic usage

Example: Setting Initial Font

In this example, the initial font displayed in the dialog is set to Arial with a size of 12 points.

from PyQt6.QtWidgets import QApplication, QFontDialog, QPushButton
from PyQt6.QtGui import QFont  # Import QFont class

def open_font_dialog():
   initial_font = QFont("Arial", 12)
   font, ok = QFontDialog.getFont(initial_font)
   if ok:
      print("Selected Font:", font.toString())

app = QApplication([])
button = QPushButton("Select Font")
button.clicked.connect(open_font_dialog)
button.show()
app.exec()

Output

The above code produces the following output −

pyqt qfontdialog example 1
Advertisements