Home » PyQt5 QFontDialog widget

PyQt5 QFontDialog widget

1 Year Subscription
Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification

In this article we look at the QFontDialog

It provides a dialog widget for selecting a font and they are used to select different fonts and various properties such as size and style

It is popup type widget in PyQt5

The class contains a static method called getFont(). It displays the font selector dialog.

The setCurrentFont() method sets the default Font of the dialog.

Example

This is a basic example

The following example has a button and a label. When the button is clicked, a font dialog pops up. The font chosen by the user along with any other settings is applied to the text on the label.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, \
    QPushButton, QSizePolicy, QLabel, QFontDialog


class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        btn = QPushButton('Change font properties', self)
        btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        btn.move(20, 20)
        btn.clicked.connect(self.showDialog)

        vbox = QVBoxLayout()
        vbox.addWidget(btn)

        self.lbl = QLabel('This is some test text for the font', self)
        self.lbl.move(130, 20)

        vbox.addWidget(self.lbl)
        self.setLayout(vbox)

        self.setWindowTitle('Font Dialog')
        self.setGeometry(300, 300, 250, 200)
        self.show()

    def showDialog(self):
        font, ok = QFontDialog.getFont()
        if ok:
            self.lbl.setFont(font)


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

When you run this you will see the following

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More