Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Detecting when a Qt application has been switched to the background and when resumed

From Wiki
Jump to: navigation, search

This code snippet shows how to create an event filter in Qt C++ to detect when an app has been switched to the background and when it is resumed. Note that for apps using Qt Quick Components for Symbian, the Symbian Element foreground property can be used instead.

Article Metadata
Tested with
SDK: Qt SDK 1.0
Devices(s): Nokia N8-00, Nokia E7-00, Nokia N9
Platform(s): Symbian, Maemo, Harmattan, Qt 4.7
Keywords: deactivation, activation, events
Created: makivioj (28 Jun 2011)
Last edited: kiran10182 (31 Oct 2013)



In many Qt supported platforms it is possible to switch the application to the background and resume to it when needed. For example in Harmattan the applications can be swiped to the background, and in Symbian^3 the switching can be done via the menu button. It is common that applications need to run some operations when these kinds of deactivation and activation events happen. For example games usually need to be paused when they are switched to the background. Also in other kinds of applications the unnecessary operations can be paused to free processing and memory resources.


In Qt this can be handled by listening the ApplicationDeactivate and ApplicationActivate events and reacting to them accordingly. The QObject class has an eventFilter method, which can be overridden in some class derived from QObject. Those earlier mentioned events can be listened in this reimplemented method. The class that reimplements the eventFilter method is then installed as an event filter for the QApplication object.

This methodology is used in Qt GameEnabler.



EventFilter derived from QObject

bool EventFilter::eventFilter(QObject *obj, QEvent *event) 
if (event->type() == QEvent::ApplicationDeactivate) {
// The application deactivation can be handled here
return true; // The event is handled
if (event->type() == QEvent::ApplicationActivate) {
// The application activation can be handled here
return true;
return QObject::eventFilter(obj, event); // Unhandled events are passed to the base class


#include "eventfilter.h"  
int main(int argc, char *argv[])
QApplication app(argc, argv);
EventFilter eventFilter;
app.installEventFilter(&eventFilter); // Installing the event filter


This code snippet demonstrated how to detect when a Qt application has been switched to the background and when it is resumed.

This page was last modified on 31 October 2013, at 19:20.
79 page views in the last 30 days.