This example creates a simple window with a button and a line-edit in a layout. It also shows how to connect a signal to a slot, so that clicking the button adds some text to the line-edit.
import sys
from PyQt5.QtWidgets import QApplication, QWidget
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
w.resize(250, 150)
w.move(300, 300)
w.setWindowTitle('Hello World')
w.show()
sys.exit(app.exec_())
Analysis
app = QtWidgets.QApplication(sys.argv)
Every PyQt5 application must create an application object. The sys.argv parameter is a list of arguments from a command line. Python scripts can be run from the shell.
w = QWidget()
The QWidget
widget is the base class of all user interface objects in PyQt5. We provide the default constructor for QWidget
. The default constructor has no parent. A widget with no parent is called a window.
w.resize(250, 150)
The resize()
method resizes the widget. It is 250px wide and 150px high.
w.move(300, 300)
The move()
method moves the widget to a position on the screen at x=300, y=300 coordinates.
w.setWindowTitle('Hello World')
Here we set the title for our window. The title is shown in the titlebar.
w.show()
The show()
method displays the widget on the screen. A widget is first created in memory and later shown on the screen.
sys.exit(app.exec_())
Finally, we enter the mainloop of the application. The event handling starts from this point. The mainloop receives events from the window system and dispatches them to the application widgets. The mainloop ends if we call the exit()
method or the main widget is destroyed. The sys.exit()
method ensures a clean exit. The environment will be informed how the application ended.
The exec_()
method has an underscore. It is because the exec is a Python keyword. And thus, exec_()
was used instead.