Why does eventFilter() call parent().eventFilter()

  • Looking through at existing code I have inherited several "pages" --- which are QWidgets on a QStackedWidget --- override the QWidget::eventFilter(), like this (Python, but I'm quite sure you can mentally translate this to C++):

        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)

    So it's to achieve saving of table view columns state, fair enough.

    I figured that this gets called when I close the whole program down (can't use QWidget::closeEvent() for that).

    What I don't get is: why does this need to propagate this event to its parent (self.parent() == this.parent())?? That's an "unusual" thing to do. And wouldn't its parent already have received, or be due to receive, that event, so it might hit there twice now? Could someone enlighten me?

  • Lifetime Qt Champion

    Yes, that is a bit odd by normal standards, i think.
    Normally you would return false for (i did not use it)
    or true for "i did use it".
    And Qt handles the propagation.
    But it could be a design where the parent must do something and they chained it this way.
    But does the actual parent have a filter installed?

  • Lifetime Qt Champion


    I wonder if the original developer mixed the concept of parent and mother classe.

    AFAIK, that line should be return super(ClassName, self).eventFilter(watched, event).

  • @SGaist
    I've never read up on it, but I assume super(ClassName, self) is just super()? Yes, I could perfectly well understand if the code were super().eventFilter(watched, event), it's because it's parent() that I was asking about this.

    Tomorrow I will look at @mrjj's "But does the actual parent have a filter installed?" I'm assuming that because all these are "pages" the parent() will be the QStackedWidget? Even if it wants the event, it seems to me this code is in several pages so they will be forwarding the event to the same parent multiple times, which also seems odd.

  • @mrjj, @SGaist
    Well, parent() of these "page widgets" is indeed the QStackedWidget. Not sub-classed, so no eventFilter() on it in my code. I can see no reason why, as the code stood, every event arriving at each "page" should be forwarded on to the QStackedWidget, and for that matter not forwarded to base widget class.

    So I have changed all of these from return self.parent().eventFilter(watched, event) to return super().eventFilter(watched, event), which at least makes sense to me. No differences/ill-effects observed, so hopefully that's it.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.