PyQt5 Label

We will learn to use label widget QLabel in this tutorial.

Label Widget

We’re going to add two labels to our window, where one of those labels is going to hold some text and one of those labels is going to hold an image.

QLabel.py
import sys
from PyQt5 import QtWidgets, QtGui

def basicWindow():
    app = QtWidgets.QApplication(sys.argv)
    windowExample = QtWidgets.QWidget()
    labelA = QtWidgets.QLabel(windowExample)
    labelB = QtWidgets.QLabel(windowExample)
    labelA.setText('Label Example')
    labelB.setPixmap(QtGui.QPixmap('python.jpg'))
    windowExample.setWindowTitle('Label Example')
    windowExample.setGeometry(100, 100, 300, 200)
    labelA.move(100, 40)
    labelB.move(120, 120)
    windowExample.show()
    sys.exit(app.exec_())

basicWindow()

Where,

labelA = QtWidgets.QLabel(w)

The first label labelA is a QtWidgets.QtLabel and the QtWidgets-w is in parentheses because it tells the program that the label labelA is added to the window w.

labelA.setText('Label Example')

labelA.setText sets the text in the label.

windowExample.setGeometry(100, 100, 300, 200)

It sets the window size to be (300, 200) and left upper corner coordinate to be (100, 100). You could refer to the setGeometry explanation in last section.

labelA.move(100, 40)
labelB.move(120, 120)

move() method moves the label to the direction of right and down. Like labelA.move(100, 40) moves the labelA to the coordinate of (100, 40) relative to the left-upper corner of the window.

labelB.setPixmap(QtGui.QPixmap('globe.png'))

It displays images in the labelB. QPixmap is the module in QtGui and it takes an image of Qt.

PyQt5 Label

QLabel Set Font

In the example above, we use the default font in label widget, and you could specify the preferred font like size, weight and font family of the label text.

QLabel_Set Font.py
import sys
from PyQt5 import QtWidgets, QtGui

def basicWindow():
    app = QtWidgets.QApplication(sys.argv)
    windowExample = QtWidgets.QWidget()
    labelA = QtWidgets.QLabel(windowExample)
    labelB = QtWidgets.QLabel(windowExample)
    labelA.setText('Times Font')
    labelA.setFont(QtGui.QFont("Times", 12, QtGui.QFont.Bold))
    labelB.setText('Arial Font')
    labelB.setFont(QtGui.QFont("Arial", 14, QtGui.QFont.Black))
    windowExample.setWindowTitle('Label Example')
    windowExample.setGeometry(100, 100, 300, 200)
    labelA.move(100, 40)
    labelB.move(100, 120)
    windowExample.show()
    sys.exit(app.exec_())

basicWindow()
labelA.setFont(QtGui.QFont("Times", 12, QtGui.QFont.Bold))

setFont() method sets the font of the label. The QFont class specifies a font with specific attributes.

PyQt5 Label Set Font