O'Reilly logo

Programming with Qt, 2nd Edition by Matthias Kalle Dalheimer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 16. Advanced Event Handling

So far, you have seen how to respond to events by connecting to signals or by reimplementing event handlers. This response suffices for most applications, but there are cases in which you need to do a little bit more. In this chapter, we will discover ways to override the standard event-handling mechanisms, notably by using event filters and synthetic events.

Event Filters

An event filter is an object that gets all events for another object and has the chance to react to an event before the original addressee of the event can do so. This is useful if you want to override the behavior of an object, but do not want to or cannot change the class of that object itself. Another possible scenario for using an event filter is when you want to add a certain function to a lot of widgets in your application, but don’t want to subclass every class used there. We will see such an application in a moment.

There are two steps to using an event filter: writing the event-filter code and installing it. You write an event filter by reimplementing the method eventFilter() in a class derived from QObject. Often, this is a widget itself. This method has two parameters: a pointer to the object for which the event was originally meant, and a pointer to an object of the class QEvent that encapsulates the event data.

The event handler can do anything it wants. It can even delete the object for which the event was meant. When it is done with the event, it must return ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required