PyQt - Resize Event



In PyQt a resize event happens when the dimensions of a widget shift. This adjustment may result from user actions like adjusting a windows size or from changing the widgets dimensions. Managing resize events is essential to maintain the applications layout responsiveness and to accommodate screen sizes or user choices.

Handling Resize Events in PyQt

PyQt provides a built-in resizeEvent() method that allows developers to respond to resize events for widgets. By overriding this method in custom widget classes, you can execute specific actions whenever the widget's size changes. This feature helps developers implement dynamic layouts, adjust widget properties, or trigger other functions based on the widget's size.

Methods Associated with Resize Events

Method Description
resizeEvent(self, QResizeEvent) Called when the widget is resized.
event(QEvent) Reimplemented from QWidget.event().
updateGeometry() Updates the widget's geometry.

Example 1: Handling Resize Event for a Custom Widget

In the below example, we define a custom widget class that inherits from QWidget. It overrides the resizeEvent() method to print the size of the widget whenever it's resized. When the widget is resized, the resizeEvent() method is automatically called, allowing us to execute custom code in response to the resize event.

from PyQt6.QtWidgets import QApplication, QWidget
from PyQt6.QtCore import QSize

class CustomWidget(QWidget):
   def __init__(self):
      super().__init__()

   def resizeEvent(self, event):
      print("Widget resized to:", event.size())

if __name__ == '__main__':
   app = QApplication([])
   widget = CustomWidget()
   widget.resize(300, 200)
   widget.show()
   app.exec()

Output

Whenever you change the widget size, the size of the widget is printed to console.

Widget resized to: PyQt6.QtCore.QSize(356, 163)
Widget resized to: PyQt6.QtCore.QSize(357, 163)
Widget resized to: PyQt6.QtCore.QSize(358, 163)
Widget resized to: PyQt6.QtCore.QSize(359, 163)

Example 2: Dynamically Adjusting Widget Properties on Resize

In this example, a custom widget is created with a QLabel. The text of the label changes dynamically based on the width of the widget. When the widget's width is less than 200 pixels, the label displays "Too small!", otherwise it displays "Resize me!".

from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout

class DynamicWidget(QWidget):
   def __init__(self):
      super().__init__()
      self.label = QLabel("Resize me!")
      layout = QVBoxLayout(self)
      layout.addWidget(self.label)

   def resizeEvent(self, event):
      if event.size().width() < 200:
         self.label.setText("Too small!")
      else:
         self.label.setText("Resize me!")

if __name__ == '__main__':
   app = QApplication([])
   widget = DynamicWidget()
   widget.resize(300, 200)
   widget.show()
   app.exec()

Output

The above code produces the following result −

pyqt resize event example 2
Advertisements