PyQt - Hide Event



In PyQt, the hideEvent method is a member function of QWidget, the base class of all user interface objects. This method is invoked when a widget becomes invisible, either due to user action or programmatically through code.

Methods Used in PyQt - Hide Event

The different methods used in PyQt for managing the hide event and their short working description of each method are as follows −

Method Description
hideEvent(event) Invoked when the widget becomes invisible either due to user action or programmatically through code.
setVisible(visible) Sets the visibility of the widget to the specified boolean value.
isVisible() Returns True if the widget is visible; otherwise, returns False.

Usage of hideEvent in PyQt

  • Managing Widget Visibility − The main use of the hideEvent method is to manage the visibility of widgets in PyQt applications. By overriding this method, developers can execute specific actions or perform cleanup tasks when a widget becomes hidden.
  • Customizing Behavior on Hide − We can customize the behavior of widgets when they are hidden. This includes executing certain actions, updating states, or triggering other events based on the hide event.
  • Conditional Visibility Handling − We can use the hide event to implement conditional visibility handling based on specific conditions or application states. This allows for dynamic control over when and how widgets are hidden.

Example: Toggling Widget Visibility

In the below example, we create a widget with a button to toggle its visibility. The hideEvent method is overridden to print a message when the widget becomes hidden.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout

class ToggleWidget(QWidget):
   def __init__(self):
      super().__init__()
      self.initUI()

   def initUI(self):
      self.button = QPushButton("Toggle Widget")
      self.button.clicked.connect(self.toggle_visibility)
      layout = QVBoxLayout()
      layout.addWidget(self.button)
      self.setLayout(layout)

   def hideEvent(self, event):
      print("Widget is now hidden")

   def toggle_visibility(self):
      self.setVisible(not self.isVisible())

def main():
   app = QApplication(sys.argv)
   widget = ToggleWidget()
   widget.show()
   sys.exit(app.exec())

if __name__ == "__main__":
   main()

Output

The above code produces the following output −

pyqt hide event example 1
Advertisements