10

I'm using python3 and pyqt4 and I want some code to run every time my QMainWindow is resized.I would like something like this

self.window.resized.connect(self.resize)

but resized is not a builtin function or method. Can anyone help.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
chicken-me
  • 131
  • 1
  • 1
  • 6

2 Answers2

19

You must override the resizeEvent method.

from PyQt4 import QtCore, QtGui
import sys

class MainWindow(QtGui.QMainWindow):
    def resizeEvent(self, event):
        print("resize")
        QtGui.QMainWindow.resizeEvent(self, event)



app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Why is the line `QtGui.QMainWindow.resizeEvent(self, event)` needed in the function? In pyqt5 this is: `QtWidgets.QMainWindow.resizeEvent(self, event)`. – ZF007 May 08 '20 at 23:45
  • @ZF007 When a method is overridden and you don't call the parent method you can remove the default behavior that can cause problems (unless it's an abstract method) – eyllanesc May 08 '20 at 23:53
7

For anyone who is looking for it, here is a PyQt5 solution. This is pretty much @eyllancesc code, so all thanks goes to them. There are only a few modifications needed for PyQt5

from PyQt5 import QtCore, QtGui, QtWidgets
import sys

class MainWindow(QtWidgets.QMainWindow):
    def resizeEvent(self, event):
        print("Window has been resized")
        QtWidgets.QMainWindow.resizeEvent(self, event)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Jacob Ward
  • 221
  • 2
  • 12
  • According to my research, the best option for adaptive resizing is using resizeEvent like you suggested, thanks – ati ince May 30 '22 at 14:29