Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
QStackedWidget pages and closeEvent()/eventFilter()
JonB last edited by
I have a mature product with uncommented code written by people who like spaghetti. I have come across code I do not understand. However, I must be careful not to change it if I do not understand the behaviour/change in behaviour.
The app has a main window, with a
QStackedWidgetwhich holds all its "sub-pages" (
QWidgets), selectable via a toolbar.
Various of these pages wish to save their state (or whatever action) on main window close. (Please do not suggest on destruction; there are issues with that from Python, and I wish to perform the action on close.)
I am used to using a
QWidget::closeEvent()override for this. However, left to its devices, although the main window gets a close event the
QStackedWidgetpages do not (tested empirically).
The current code for detecting in these sub-pages is instead:
def eventFilter(self, watched, event): if watched == self.window() and event.type() == QEvent.Close: saveState(__name__, self.grid.header()) return self.parent().eventFilter(watched, event)
The bit I don't get is the use of
QMainWindow. Why is this widget deferring to the parent's
eventFilter(), when the usual pattern for an override is
super()is the base class in Python? It seems to me: I will have many of these pages'
eventFilter()getting called on main close, so they will call the main window's
eventFilter()that many times, which seems odd?
I suppose a different approach would be for the main window/stacked widget to explicitly call
QWidget.close()on each & every widget in the stacked widget, then I would get the
closeEvent()on them. However that would require changing the calling code somewhere to do so, whereas (for right or for wrong) at the moment the
eventFilter()of the sub-pages is getting called automatically without me having to do anything, so I'd rather like to stick with it...?