[파이썬] PyQt 폰트 선택 다이얼로그 (`QFontDialog`)

In this blog post, we will explore how to use the QFontDialog in PyQt to allow users to select a font from a dialog box. With the help of this dialog, users can choose the desired font style, size, and other properties for their text.

Getting started

Before we proceed, make sure you have PyQt installed in your Python environment. You can install it using pip:

pip install PyQt5

Once you have PyQt installed, you can import the necessary modules:

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

The QFontDialog class is located in the QtWidgets module, so we import it along with other necessary classes.

Creating the font selection dialog

To create the font selection dialog, we need to create a new instance of the QFontDialog class. We can use the getFont() method of the dialog class to open the dialog and get the selected font. Here’s an example:

def show_font_dialog():
    font, ok = QFontDialog.getFont()
    
    if ok:
        # Apply the selected font to your text or widget
        your_widget.setFont(font)

In the above code, we call the getFont() method of the QFontDialog class which opens the font selection dialog. The method returns the selected font and a boolean indicating if the user clicked “OK” or “Cancel”.

If the user clicks “OK” (ok is True), we can then apply the selected font to our text or widget using the setFont() method.

Putting it all together

Let’s create a simple example to demonstrate the usage of the QFontDialog.

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        
        self.text_edit = QLineEdit()
        self.select_button = QPushButton("Select Font")
        
        layout = QVBoxLayout()
        layout.addWidget(self.text_edit)
        layout.addWidget(self.select_button)
        
        self.setLayout(layout)
        
        self.select_button.clicked.connect(self.show_font_dialog)
        
    def show_font_dialog(self):
        font, ok = QFontDialog.getFont()
        
        if ok:
            self.text_edit.setFont(font)

In the example above, we create a MainWindow class which inherits from QWidget. We add a QLineEdit widget to display the selected font and a QPushButton to trigger the font selection dialog.

When the user clicks the button, the show_font_dialog() method is called. Inside this method, we open the font selection dialog and apply the selected font to the text input widget.

Conclusion

In this blog post, we explored how to use the QFontDialog in PyQt to allow users to select a font for their text. By following the steps outlined above, you can easily incorporate font selection functionality into your PyQt applications. This makes it convenient for users to personalize the appearance of their text according to their preferences.