QLabel

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

By default, the label is aligned left in horizontal direction and center in vertical direction, but it can be adjusted through the setAlignment() method.

Let’s create a label and try some of the methods related to the label’s style.


Example

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 displayed in the vertical box.


Description

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

Create a Qlabel widget. Enter the label text and parent widget to the constructor.

You can adjust the placement of labels with the setAlignment() method. If you set it with Qt.AlignCenter, it will be aligned in the center both horizontally and vertically.


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

We made a font for the label. Set the font size with the setPointSize() method.


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

Create a second label and set it to the center (Qt.AlignVCenter) in vertical direction only.

To align in center horizontally, enter At.AlignHCenter.


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

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

Make the font bold with setBold (true). This time, because the font size isn’t set, it becomes 13, the default size.


Results

../_images/4_2_qlabel.png ../_images/4_2_qlabel_mac.png

Figure 5-2. Make label.


Prev/Next

Next :