1 - Creation of a QLabelPyQt5
To create labels within a window, PyQt5 offers us the QLabel class. You just have to instantiate this class by adding the parent container as a parameter:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
app = QApplication(sys.argv)
widget = QWidget()
widget.setGeometry(50,50,320,200)
widget.setWindowTitle("Label Example")
# create a QLabel
qlabel = QLabel(widget)
qlabel.setText("Hello World !")
# define the qlabel dimensions & position
qlabel.setGeometry(50 , 50 , 200 , 50)
widget.show()
sys.exit(app.exec_())
2 - Use a design style for a QLabel
A QLabel object has the setStyleSheet() method which allows you to add a qss (Qt Style Sheet) style:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
app = QApplication(sys.argv)
widget = QWidget()
widget.setGeometry(50,50,350,200)
widget.setWindowTitle("Label Example")
# create a QLabel
qlabel = QLabel(widget)
qlabel.setText("Hello World !")
# define the qlabel dimensions & position
qlabel.setGeometry(50 , 50 , 250 , 50)
# Use QSS designe
qlabel.setStyleSheet("background: darkblue; border: 2px solid red; color:yellow; font:broadway; font-size:36px;")
widget.show()
sys.exit(app.exec_())
3 - QLabel PyQt5 according to the object approach
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
class Window(QWidget):
def __init__(self , window):
super().__init__()
self.window = window
# create build method
def build(self):
self.window.setWindowTitle("Example of QLabel by OOP approach")
self.window.setGeometry(100 , 100 , 400 , 200)
# create a QLabel
myLabel = QLabel(self.window)
myLabel.setText("Example of QLabel by object approach !")
myLabel.setGeometry(50 , 50 , 300 , 50)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = QWidget()
myWin = Window(win)
myWin.build()
win.show()
app.exec_()
Younes Derfoufi
my-courses.net
my-courses.net