Creating First PyQt5 Application - Hello World Program
Last Update : 14 Oct, 2022In this tutorial, you will learn how to create a basic "Hello World" application using PyQt5. This application shows the simple "Hello World" text on the Qt GUI window.
Also, PyQt5 is a good module that is used to develop desktop or graphical user interface applications. Also, you need to make sure that you have to PyQt5 installed before starting this tutorial.
PyQt5 "Hello Word" Program
Let's consider the following example. After running this example, you can see a desktop window with the "Hello World” text.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
def window():
app = QApplication(sys.argv)
widget = QWidget()
textLabel = QLabel(widget)
textLabel.setText("Hello World")
textLabel.move(150,100)
widget.setGeometry(60,60,400,350)
widget.setWindowTitle("PyQt5 Hello Word Program")
widget.show()
sys.exit(app.exec_())
if __name__ == '__main__':
window()
This program produces the following result -:
How to Work the above Example Code
To run the PyQt5 application, First, you need to import the below codes on top of the codes of your program.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
These codes are imported from the modules of PyQt5 and sys(The sys module comes packaged with Python).
Use the following codes to initialize the PyQt5 application.
app = QApplication(sys.argv)
widget = QWidget()
Now, you need to display the "Hello World" text. But, it cannot be added immediately to a window. For that, First, you need to add a Label widget to your program.
QLabel widget uses to show a text or image. The following code line creates a QLabel, set the Label's "Hello World" text, and set the Label's horizontal & vertical position.
textLabel = QLabel(widget)
textLabel.setText("Hello World")
textLabel.move(150,100)
The following code set the window starting position (60,60) and the window size (400,350) using setGeometry() method.
widget.setGeometry(60,60,400,350)
Next, you can set the window title using setWindowTitle() method and display your application window using show() method.
widget.setWindowTitle("PyQt5 Hello Word Program")
widget.show()
Follow this link to download the code of the PyQt5 Hello World Program.