PyQt QLabel

The QLabel widget is used to create text or image labels. It does not provide any interaction with the user. (See QLabel official documentation)

Labels are aligned horizontally to the left and vertically to the left, but can be adjusted through the setAlignment() method.

We're creating a label, and we're using a few methods that are relevant to the style of the label.

Related course: Create Desktop Apps with Python PyQt5

QLabel

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtCore import Qt

class MyApp(QWidget):

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

    def initUI(self):
        label1 = QLabel('First Label', self)
        label1.setAlignment(Qt.AlignCenter)

        label2 = QLabel('Second Label', self)
        label2.setAlignment(Qt.AlignVCenter)

        font1 = label1.font()
        font1.setPointSize(20)

        font2 = label2.font()
        font2.setFamily('Times New Roman')
        font2.setBold(True)

        label1.setFont(font1)
        label2.setFont(font2)

        layout = QVBoxLayout()
        layout.addWidget(label1)
        layout.addWidget(label2)

        self.setLayout(layout)

        self.setWindowTitle('QLabel')
        self.setGeometry(300, 300, 300, 200)
        self.show()

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

Two labels were placed in a vertical box.

pyqt qlabel

Related course: Create Desktop Apps with Python PyQt5

Description

label1 = QLabel('First Label', self)
label1.setAlignment(Qt.AlignCenter)

You have created one QLabel widget. Enter label text and parent widgets in the constructor.

You can set the placement of labels with the setAlignment() method.

If you set it to Qt.AlignCenter, both horizontal and vertical orientations will be in the center.

font1 = label1.font()
font1.setPointSize(20)

You have created one font to be used for the label.

The setPointSize() method allows you to set the size of the font.

label2 = QLabel('Second Label', self)
label2.setAlignment(Qt.AlignVCenter)

Create a second label, this time with the center (Qt.AlignVCenter) only in the vertical direction.

To set it to the center in a horizontal direction, you can enter Qt.AlignHCenter.

font2 = label2.font()
font2.setFamily('Times New Roman')
font2.setBold(True)

Create a font to set on the second label, and set the font type to 'Times New Roman' with the setFamily() method.

Set the font to setBold (True) to True.

This time, it is set to the default size of 13 because the font has not been sized.