1. Simple case of PyQt5
Here is a simple example showing a small window. However, we can do a lot with this window. We can resize it, maximize or minimize it. This requires a lot of coding. Someone has already written this function. Since it is repeated in most applications, no recoding is required. PyQt5 is an advanced toolkit. The code example below could easily be hundreds of lines if we were coding in a lower level toolkit.
simple.py
#!/usr/bin/python """ ZetCode PyQt5 tutorial In this example, we create a simple window in PyQt5. Author: Jan Bodnar Website: zetcode.com """ import sys from PyQt5.QtWidgets import QApplication, QWidget def main(): app = QApplication(sys.argv) w = QWidget() w.resize(250, 150) w.move(300, 300) w.setWindowTitle('Simple') w.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
The code example above displays a small window on the screen.
CSDN QT technical articles are recommended: Qt development essential technology stack learning routes and materials
import sys
from PyQt5.QtWidgets import QApplication, QWidget
Here we provide the necessary imports. The basic widgets are located in the module in PyQt5.QtWidgets
app = QApplication(sys.argv)
Every PyQt5 application must create an application object. The sys.argv argument is a list of arguments from the command line. Python scripts can be run from the shell. This is a way for us to control script startup.
w = QWidget()
QWidget widgets are the base class for all user interface objects in PyQt5. We provide a default constructor for QWidget. The default constructor has no parent. A widget without a parent is called a window.
w.resize(250, 150)
The resize method resizes the widget. It is 250 pixels wide and 150 pixels high.
w.move(300, 300)
The move method moves the widget to the position on the screen at x=300, y=300 coordinates.
w.setWindowTitle('Simple')
We use setWindowTitle to set the title of the window. The title is displayed in the title bar.
w.show()
The show method displays the widget on the screen. Widgets are first created in memory and then displayed on the screen.
sys.exit(app.exec_())
Finally, we enter the main loop of the application. Event handling starts at this point. The main loop receives events from the window system and dispatches them to application widgets. The main loop 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 told how the application ended.
The exec_ method has an underscore. This is because exec is a Python keyword. Therefore, exec_ is used.
2. Add an icon to the application
The application icon is a small image, usually displayed in the upper left corner of the title bar. In the following example we will show how to do this in PyQt5. We will also introduce some new methods.
Some environments do not display icons in the title bar. We need to enable them. If you don't see any icons, see my answer on Stackoverflow for a solution.
icon.py
#!/usr/bin/python """ ZetCode PyQt5 tutorial This example shows an icon in the titlebar of the window. Author: Jan Bodnar Website: zetcode.com """ import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtGui import QIcon class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setGeometry(300, 300, 300, 220) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('web.png')) self.show() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
The preceding examples are coded in procedural style. The Python programming language supports procedural and object-oriented programming styles. Programming in PyQt5 means programming in OOP.
class Example(QWidget): def __init__(self): super().__init__() ...
The three things in object-oriented programming are classes, data, and methods. Here, we create a new class called "Example". The Example class inherits from the QWidget class. This means that we call two constructors: the first for the example class and the second for the inherited class. The super method returns the parent object of the Example class, and we call its constructor. The __init__ method is a constructor in the Python language.
self.initUI()
The creation of the GUI is delegated to the initUI method.
self.setGeometry(300, 300, 300, 220) self.setWindowTitle('Icon') self.setWindowIcon(QIcon('web.png'))
All three methods are inherited from the QWidget class. setGeometry does two things: it positions the window on the screen and sets its size. The first two arguments are the x and y position of the window. The third is the width and the fourth is the height of the window. In fact, it combines resizing and moving methods in one method. The last method sets the application icon. For this, we create a QIcon object. QIcon receives the path to the icon to display.
def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_())
Create application and sample objects. The main loop starts.
3. Display tooltips in PyQt5
We can help with balloons for any of our widgets.
tooltip.py
#!/usr/bin/python """ ZetCode PyQt5 tutorial This example shows a tooltip on a window and a button. Author: Jan Bodnar Website: zetcode.com """ import sys from PyQt5.QtWidgets import (QWidget, QToolTip, QPushButton, QApplication) from PyQt5.QtGui import QFont class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): QToolTip.setFont(QFont('SansSerif', 10)) self.setToolTip('This is a <b>QWidget</b> widget') btn = QPushButton('Button', self) btn.setToolTip('This is a <b>QPushButton</b> widget') btn.resize(btn.sizeHint()) btn.move(50, 50) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Tooltips') self.show() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
In this example, we show tooltips for two PyQt5 widgets.
QToolTip.setFont(QFont('SansSerif', 10))
This static method sets the font used to render tooltips. We use 10pt SansSerif font.
self.setToolTip('This is a <b>QWidget</b> widget')
To create a tooltip, we call the setTooltip method. We can use rich text formatting.
btn = QPushButton('Button', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
We create a button widget and set a tooltip for it.
btn.resize(btn.sizeHint())
btn.move(50, 50)
The buttons are resizing and moving across the window. The sizeHint method provides the recommended size for the button.
CSDN QT technical article recommendation: Qt development essential technology stack learning routes and materials
Fourth, close the window
The obvious way to close a window is to click the x mark on the title bar. In the next example, we'll show how to programmatically close a window. We'll briefly cover signals and slots. Below is the constructor for the QPushButton widget we used in our example.
QPushButton(string text, QWidget parent = None)
The text parameter is the text that will be displayed on the button. The parent is the widget where we place the button. In our case it will be a QWidget. The widgets of an application form a hierarchy. In this hierarchy, most widgets have their parents. A widget without a parent is a top-level window.
quit_button.py
#!/usr/bin/python """ ZetCode PyQt5 tutorial This program creates a quit button. When we press the button, the application terminates. Author: Jan Bodnar Website: zetcode.com """ import sys from PyQt5.QtWidgets import QWidget, QPushButton, QApplication class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): qbtn = QPushButton('Quit', self) qbtn.clicked.connect(QApplication.instance().quit) qbtn.resize(qbtn.sizeHint()) qbtn.move(50, 50) self.setGeometry(300, 300, 350, 250) self.setWindowTitle('Quit button') self.show() def main(): app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main()
In this example, we created an exit button. After the button is clicked, the application terminates.
qbtn = QPushButton('Quit', self)
We create a button. The button is an instance of the QPushButton class. The first parameter of the constructor is the label of the button. The second parameter is the parent widget. The parent widget is the example widget, which is an inherited QWidget.
qbtn.clicked.connect(QApplication.instance().quit)
The event handling system in PyQt5 is built using the signal and slot mechanism. If we click the button, the click signal is emitted. Slots can be Qt slots or any Python callable.
The QCoreApplication retrieved using QApplication.instance contains the main event loop - it handles and dispatches all events. The clicked signal is connected to the exit method that terminates the application. Communication is done between two objects: sender and receiver. The sender is the button and the receiver is the application object.