Question

There are many explanations on the web which explain how to handle exceptions in Qt. And they do it similarly, with one difference : some are returning true (this), while others are returning false (this, this and this).

So, what should QApplication::notify() return when it catches an exception?

QT doc tells :

Sends event to receiver: receiver->event(event). Returns the value that is returned from the receiver's event handler. Note that this function is called for all events sent to any object in any thread.

For certain types of events (e.g. mouse and key events), the event will be propagated to the receiver's parent and so on up to the top-level object if the receiver is not interested in the event (i.e., it returns false).

Was it helpful?

Solution

notify returns whatever QObject::event would return. If the event was processed and you don't want to propagate the event any further, you should return true, otherwise return false. Those are Qt's semantics.

When there is an exception thrown by the event handler, it's generally anyone's guess as to whether the event should be handled further or not.

There are two lines of reasoning, of course at odds with each other:

  1. The thrown exception indicates that the event was not handled. So you should return false.

  2. The exception was thrown because the event was being handled - it's likely to come from nontrivial code. So it was simply a handling of event, but it failed, so you should return true.

Qt's semantics seem to line up better with the first answer - that of returning false. In practice it probably doesn't matter at all unless the events are handled by widgets, where you can run into misbehavior if events vanish too early. So, false is probably overall a better choice.

Recall event propagation in widgets. If a child widget doesn't consume (handle) an event, the event method, and thus notify, will return false, and the event will be passed to the widget's parent. If you return true where a successful call to event would return false, you're effectively filtering the event out from the underlying parent widget. This is the source of possible misbehavior.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top