Customizing widget behavior with PyQt event handling
Python PyQt Basic: Exercise-9 with Solution
Write a Python program that overrides a specific event handler to customize widget behavior using PyQt.
QApplication Class: The QApplication class manages the GUI application's control flow and main settings.
QWidget: The QWidget class is the base class of all user interface objects.
Qt module: PyQt5 is a set of Python bindings for the Qt application framework. It allows us to use Qt, a popular C++ framework, to create graphical user interfaces (GUIs) in Python.
import sys from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtCore import Qt class CustomWidget(QWidget): def __init__(self): super().__init__() def mousePressEvent(self, event): # Override the mousePressEvent to customize behavior if event.button() == Qt.LeftButton: print("Left mouse button clicked") elif event.button() == Qt.RightButton: print("Right mouse button clicked") def main(): app = QApplication(sys.argv) window = CustomWidget() window.setWindowTitle("Custom Widget Example") window.setGeometry(100, 100, 400, 300) window.show() sys.exit(app.exec_()) if __name__ == "__main__": main()
In the exercise above -
- Import the necessary modules.
- Create a custom widget class "CustomWidget" that inherits from "QWidget".
- Inside the CustomWidget class, we override the mousePressEvent event handler to customize its behavior. Depending on which mouse button was clicked (left or right), we print a message.
- In the main function, we create a "QApplication", instantiate our custom widget (CustomWidget), set the window's title and geometry, and show the window.
- When you run this program, it displays a window and start the application's event loop.
- When you click the left or right mouse button inside the widget, it prints a corresponding message to the console.
Left mouse button clicked Left mouse button clicked Right mouse button clicked Left mouse button clicked Right mouse button clicked
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Python: Tips of the Day
Summing a sequence of numbers (calculating the sum of zero to ten with skips):
>>> l = range(0,10,2) >>> sum(l) 20
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook