PyQt - QLabel Widget


A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. Plain text, hyperlink or rich text can be displayed on the label.

The following table lists the important methods defined in QLabel class −

Given below are the most commonly used methods of QLabel.

Sr.No. Methods & Description
1

setAlignment()

Aligns the text as per alignment constants

Qt.AlignLeft

Qt.AlignRight

Qt.AlignCenter

Qt.AlignJustify

2

setIndent()

Sets the labels text indent

3

setPixmap()

Displays an image

4

Text()

Displays the caption of the label

5

setText()

Programmatically sets the caption

6

selectedText()

Displays the selected text from the label (The textInteractionFlag must be set to TextSelectableByMouse)

7

setBuddy()

Associates the label with any input widget

8

setWordWrap()

Enables or disables wrapping text in the label

Signals of QLabel Class

linkActivated If the label containing embedded hyperlink is clicked, the URL will open. setOpenExternalLinks feature must be set to true.
linkHovered Slot method associated with this signal will be called when the label having embedded hyperlinked is hovered by the mouse.

Example

In this example, QLabel objects l2 and l4 have the caption containing hyperlink. setOpenExternalLinks for l2 is set to true. Hence, if this label is clicked, the associated URL will open in the browser. linkHovered signal of l4 is connected to hovered() function. So, whenever the mouse hovers over it, the function will be executed.

QPixmap object prepares offscreen image from python.jpg file. It is displayed as label l3 by using setPixmap() method.

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

def window():
   app = QApplication(sys.argv)
   win = QWidget() 
	
   l1 = QLabel()
   l2 = QLabel()
   l3 = QLabel()
   l4 = QLabel()
	
   l1.setText("Hello World")
   l4.setText("TutorialsPoint")
   l2.setText("welcome to Python GUI Programming")
	
   l1.setAlignment(Qt.AlignCenter)
   l3.setAlignment(Qt.AlignCenter)
   l4.setAlignment(Qt.AlignRight)
   l3.setPixmap(QPixmap("python.jpg"))
	
   vbox = QVBoxLayout()
   vbox.addWidget(l1)
   vbox.addStretch()
   vbox.addWidget(l2)
   vbox.addStretch()
   vbox.addWidget(l3)
   vbox.addStretch()
   vbox.addWidget(l4)
	
   l1.setOpenExternalLinks(True)
   l4.linkActivated.connect(clicked)
   l2.linkHovered.connect(hovered)
   l1.setTextInteractionFlags(Qt.TextSelectableByMouse)
   win.setLayout(vbox)
	
   win.setWindowTitle("QLabel Demo")
   win.show()
   sys.exit(app.exec_())
	
def hovered():
   print "hovering"
def clicked():
   print "clicked"
	
if __name__ == '__main__':
   window()

The above code produces the following output −

QLabel Widget Output