QFontDialog in PyQt6: Create and Customize Font

As a developer, working on a PyQt6 application where I needed to let users select fonts for text display. The challenge was implementing an easy way for users to choose fonts without cluttering the main interface. After exploring different options, I found that QFontDialog is the perfect solution for this task.

In this article, I will show you several ways to implement and customize QFontDialog in your PyQt6 applications.

Let us get into the topic…

QFontDialog in PyQt6

QFontDialog is a dialog widget in PyQt6 that allows users to select a font from those available on their system. It provides a complete interface for selecting font family, style, size, and other formatting options.

This dialog is particularly useful when you want to give users the ability to customize text appearance in applications such as:

  • Text editors
  • Document creation tools
  • Custom UI theme settings
  • Reporting applications

1. Basic QFontDialog Implementation in PyQt6

The simplest way to use QFontDialog is with the static getFont() method in Python. This approach requires minimal code and is perfect for quick implementations.

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget, QFontDialog
from PyQt6.QtGui import QFont

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Font Dialog Example")
        self.setGeometry(100, 100, 500, 300)

        # Create a central widget and layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)

        # Create a button to open font dialog
        self.font_button = QPushButton("Choose Font")
        self.font_button.clicked.connect(self.open_font_dialog)

        # Create a label to display text with the selected font
        self.text_label = QLabel("Sample Text - Change my font!")
        self.text_label.setFont(QFont("Arial", 12))

        # Add widgets to layout
        layout.addWidget(self.font_button)
        layout.addWidget(self.text_label)

    def open_font_dialog(self):
        # Open the font dialog and get the selected font
        font, ok = QFontDialog.getFont(self.text_label.font(), self)

        # If user clicked OK, update the label's font
        if ok:
            self.text_label.setFont(font)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

You can refer to the screenshot below to see the output.

QFontDialog in PyQt6

In this example, I’ve created a simple window with a button and a label. When you click the button, the QFontDialog opens, allowing you to select a font. After clicking OK, the label’s text is updated with the selected font.

Read QComboBox Widget in PyQt6

2. Pre-selected Font Options

Sometimes you want to initialize the dialog with specific font settings or limit the available options. Here’s how to do that:

def open_font_dialog_with_presets(self):
    # Create an initial font with specific settings
    initial_font = QFont("Times New Roman", 14, QFont.Weight.Bold, True)  # Family, size, weight, italic

    # Open the dialog with the initial font
    font, ok = QFontDialog.getFont(initial_font, self, "Select a Font for Headers")

    if ok:
        self.text_label.setFont(font)
        # You might want to save this font preference for future use
        self.save_font_preference(font)

def save_font_preference(self, font):
    # Example of saving font settings
    settings = {
        "family": font.family(),
        "size": font.pointSize(),
        "bold": font.bold(),
        "italic": font.italic(),
        "underline": font.underline()
    }
    print("Saved font settings:", settings)
    # In a real app, you might save to a file or database

You can refer to the screenshot below to see the output.

PyQt6 QFontDialog

This approach is great when you want to provide users with a starting point rather than the default system font.

3. Use QFontDialog with Options

PyQt6’s QFontDialog also supports various options to customize the dialog’s appearance and behavior. Here’s how to use them:

from PyQt6.QtWidgets import QFontDialog

def open_customized_font_dialog(self):
    options = QFontDialog.FontDialogOption.NoButtons | QFontDialog.FontDialogOption.DontUseNativeDialog

    # Create the dialog with options
    dialog = QFontDialog(self.text_label.font(), self)
    dialog.setOptions(options)
    dialog.setWindowTitle("Custom Font Selector")

    # Connect to the currentFontChanged signal for live preview
    dialog.currentFontChanged.connect(self.preview_font)

    # Show the dialog and handle result
    if dialog.exec() == QFontDialog.DialogCode.Accepted:
        selected_font = dialog.selectedFont()
        self.text_label.setFont(selected_font)

def preview_font(self, font):
    # This provides a live preview as the user explores different fonts
    self.text_label.setFont(font)

You can refer to the screenshot below to see the output.

Customize Font using QFontDialog in PyQt6

In this example, I’ve created a more customized dialog that:

  • Removes the standard buttons
  • Uses the PyQt dialog style instead of the native OS style
  • Provides a live preview of the font as the user explores options

This is particularly useful in applications where you want the font selection to blend seamlessly with your app’s design.

Check out How to Use QSlider Widget in PyQt6

4. Create a Practical Font Selection Tool

Let’s build a more practical example: a simple text editor with font selection capabilities:

import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, QPushButton, QTextEdit, 
                            QVBoxLayout, QHBoxLayout, QWidget, QFontDialog, QLabel)
from PyQt6.QtGui import QFont, QAction
from PyQt6.QtCore import Qt

class SimpleTextEditor(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Simple Text Editor")
        self.setGeometry(100, 100, 800, 600)

        # Create central widget and main layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)

        # Create toolbar-like widget for formatting buttons
        toolbar = QWidget()
        toolbar_layout = QHBoxLayout(toolbar)
        toolbar_layout.setContentsMargins(0, 0, 0, 0)

        # Font button
        self.font_button = QPushButton("Font...")
        self.font_button.clicked.connect(self.change_font)
        toolbar_layout.addWidget(self.font_button)

        # Font info label
        self.font_info = QLabel("Arial, 12pt")
        toolbar_layout.addWidget(self.font_info)
        toolbar_layout.addStretch()

        # Text editing area
        self.editor = QTextEdit()
        self.editor.setFont(QFont("Arial", 12))
        self.editor.setPlaceholderText("Start typing here...")

        # Sample text to demonstrate fonts
        sample_text = """This is a simple text editor with font selection capabilities.

You can click the Font button to change how this text appears.

Try different fonts to see which one works best for your document!
"""
        self.editor.setText(sample_text)

        # Add widgets to main layout
        main_layout.addWidget(toolbar)
        main_layout.addWidget(self.editor)

    def change_font(self):
        current_font = self.editor.currentFont()
        font, ok = QFontDialog.getFont(current_font, self, "Select Text Font")

        if ok:
            # Apply to either selected text or all text
            self.editor.setCurrentFont(font)

            # Update font info display
            font_info = f"{font.family()}, {font.pointSize()}pt"
            if font.bold():
                font_info += ", Bold"
            if font.italic():
                font_info += ", Italic"
            self.font_info.setText(font_info)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    editor = SimpleTextEditor()
    editor.show()
    sys.exit(app.exec())

This example creates a simple text editor with a font selection button. When you click the button, a QFontDialog appears, allowing you to change the font of the text. The current font information is also displayed in a label, providing visual feedback to the user.

5. Advanced QFontDialog with Custom Settings

For more advanced applications, you might want to customize the QFontDialog further or integrate it with application settings:

def setup_advanced_font_dialog(self):
    # Create a persistent dialog instance as a class member
    self.font_dialog = QFontDialog(self)

    # Set custom options
    self.font_dialog.setOption(QFontDialog.FontDialogOption.DontUseNativeDialog, True)
    self.font_dialog.setOption(QFontDialog.FontDialogOption.ScalableFonts, True)
    self.font_dialog.setOption(QFontDialog.FontDialogOption.NonScalableFonts, False)
    self.font_dialog.setOption(QFontDialog.FontDialogOption.MonospacedFonts, True)

    # Connect additional signals
    self.font_dialog.currentFontChanged.connect(self.on_font_change)
    self.font_dialog.fontSelected.connect(self.on_font_selected)

    # Add a custom widget to the dialog (for example, a color picker)
    # This requires more advanced customization and would depend on your specific needs

def show_advanced_dialog(self):
    # Set the initial font to the current application font
    self.font_dialog.setCurrentFont(QApplication.font())

    # Show the dialog non-modally
    self.font_dialog.open()

def on_font_change(self, font):
    # This gets called when the user navigates through different fonts
    # Can be used for live preview
    pass

def on_font_selected(self, font):
    # This gets called when the user finalizes a font selection
    # Perfect for applying the font to multiple elements
    self.update_application_fonts(font)

def update_application_fonts(self, font):
    # Apply the font to various application elements
    self.editor.setFont(font)
    self.title_label.setFont(QFont(font.family(), font.pointSize() + 4, QFont.Weight.Bold))
    self.status_bar.setFont(QFont(font.family(), font.pointSize() - 2))

    # Save the font preference to application settings
    self.save_font_to_settings(font)

This approach is ideal for applications that need more control over the font selection process or want to provide a more integrated experience.

Tips for Using QFontDialog Effectively

Based on my experience using QFontDialog in many PyQt applications, here are some practical tips:

  1. Remember user preferences: Save the selected fonts in your application settings and restore them when the app starts.
  2. Provide meaningful defaults: Start with a font that makes sense for your application context.
  3. Consider font accessibility: Some fonts are more readable than others. For applications where readability is crucial, you might want to limit the available fonts.
  4. Test on different platforms: Fonts available on Windows might not be available on macOS or Linux. Have fallback fonts ready.
  5. Live preview: Whenever possible, show users how their selection will look before they commit to it.

I hope you found this guide to QFontDialog in PyQt6 helpful.

In this tutorial, I explained about QFontDialog in PyQt6. I explained 5 simple methods they are: basic QFontDialog implementation in PyQt6, pre-selected font options, use QFontDialog with options, create a practical font selection tool, and advanced QFontDialog with custom settings.

You may like to read the PyQt6-related tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.