In this PyQt5 article we are going to Learn PyQt5 Event Handling with Signals and Slots, so PyQt5 is powerful and Python GUI library for building desktop applications that can run on Windows, Linux and macOS. one of the key features of PyQt5 is its robust event handling system, which enables developers to respond to user interactions and system events in flexible and efficient way. in this article we are going to explore how to use PyQt5 event handling system with signals and slots.
What are signals and slots?
Signals and slots are mechanism in PyQt5 for communicating between objects. so we can say that signal is emitted when certain event occurs, and slot is a function that is called in response to that event. Signals and slots enable developers to write code that is more reactive and event driven.
for example, let’s say we have a button in our PyQt5 application, and we want to perform certain action when the user clicks on that button. we could write an event handler function that is called when the button is clicked:
1 2 |
def handle_button_click(): print("Button clicked!") |
After that we can connect this function to the button’s clicked signal using the connect() method:
1 |
button.clicked.connect(handle_button_click) |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import sys from PyQt5.QtWidgets import QApplication, QWidget,QVBoxLayout, QLabel,QPushButton from PyQt5.QtGui import QFont class MyWindow(QWidget): def __init__(self): super().__init__() vbox = QVBoxLayout() self.button = QPushButton("Click me!", self) vbox.addWidget(self.button) self.label = QLabel("Hello") vbox.addWidget(self.label) self.button.clicked.connect(self.handle_button_click) self.setLayout(vbox) def handle_button_click(self): self.label.setText("Welcome to GeeksCoders.com") self.label.setFont(QFont("Sanserif", 15)) if __name__ == "__main__": app = QApplication(sys.argv) window = MyWindow() window.show() sys.exit(app.exec_()) |
So in the above code we have started by importing necessary modules from PyQt5. in this case we need QApplication to create our application instance, QWidget to create our window, and QPushButton to create our button, also we have used QVBoxLayout in our example to align our widgets vertically.
After that we have defined our MyWindow class, which extends from QMainWindow. in the constructor we have called super() function to initialize the QWidget base class.
(Learn PyQt5 Event Handling with Signals and Slots)
Run the code and this is the result
Learn More on Python GUI
- How to Create Label in PySide6
- How to Create Button in Python & PySide6
- How to Use Qt Designer with PySide6
- How to Add Icon to PySide6 Window
- How to Load UI in Python PySide6
- How to Create RadioButton in PySide6
- How to Create ComboBox in PySide6
- How to Create CheckBox in Python PySide6
- Responsive Applications with PyQt6 Multithreading
- Event Handling in Python and PyQt6