visheshnamdev72
Friday, 2024-09-13
In PyQt5, buttons and events in GUI play a crucial role in building interactive applications. Buttons allow users to trigger specific actions, and events are the mechanism that handles these interactions. Hereβs how buttons and events work in PyQt5:
Buttons are one of the most commonly used widgets in a GUI. In PyQt5, the QPushButton widget is used to create buttons.
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
import sys
class MyWindow(QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.initUI()
def initUI(self):
# Create a button
self.button = QPushButton('Click me', self)
# Set button size and position
self.button.setGeometry(100, 100, 100, 40)
# Connect the button to an event handler (method)
self.button.clicked.connect(self.on_button_clicked)
# Define an event handler for button click
def on_button_clicked(self):
print("Button was clicked!")
# Main application loop
def window():
app = QApplication(sys.argv)
win = MyWindow()
win.show()
sys.exit(app.exec_())
window()
2. Events in PyQt5
PyQt5 uses the signal and slot mechanism to handle events. When a user interacts with a button, it emits a signal, and a slot is a function that responds to the signal. In the example above, the buttonβs clicked signal is connected to the on_button_clicked method (a slot).
Common Button Events (Signals):
clicked: Emitted when the button is clicked.
pressed: Emitted when the button is pressed.
released: Emitted when the button is released.
Example of Connecting Events:
# Connecting a button signal to a slot (method) self.button.clicked.connect(self.on_button_clicked)
In this example, when the button is clicked, the on_button_clicked method is called.
QMainWindow, QPushButton) without rewriting code.