You could try one of these alternatives, but I have no idea whether you will get a FocusIn event for *every* change of focus between all the child widgets in your app, or only if the app itself gains focus (as you would like). Try it and see if it works.
1 - Install an eventFilter on your QApplication instance and look for FocusIn events.
2 - Derive a new class from QApplication, and reimplement the event() method.
In either case, be sure you pass the event along for further processing.
Edit: The above does not work. However, this does:
// MyApp.h
#include <QtGui/QApplication>
#include <QEvent>
#include <QtDebug>
{
Q_OBJECT
public:
MyApp( int argc, char * argv[] )
{}
{
if ( pEvent
->type
() == QEvent::ApplicationActivate ) qDebug() << "ApplicationActivate";
else if ( pEvent
->type
() == QEvent::ApplicationDeactivate ) qDebug() << "ApplicationDeactivate";
}
};
// main.cpp
#include "MyApp.h"
#include <QWidget>
int main(int argc, char *argv[])
{
MyApp a(argc, argv);
w.show();
return a.exec();
}
// MyApp.h
#include <QtGui/QApplication>
#include <QEvent>
#include <QtDebug>
class MyApp : public QApplication
{
Q_OBJECT
public:
MyApp( int argc, char * argv[] )
: QApplication( argc, argv )
{}
bool event( QEvent * pEvent )
{
if ( pEvent->type() == QEvent::ApplicationActivate )
qDebug() << "ApplicationActivate";
else if ( pEvent->type() == QEvent::ApplicationDeactivate )
qDebug() << "ApplicationDeactivate";
return QApplication::event( pEvent );
}
};
// main.cpp
#include "MyApp.h"
#include <QWidget>
int main(int argc, char *argv[])
{
MyApp a(argc, argv);
QWidget w;
w.show();
return a.exec();
}
To copy to clipboard, switch view to plain text mode
The qDebug() message is printed every time the app window is activated or deactivated. If you run up the app, "ApplicationActivate" prints as soon as the app starts up, then if you click on another app (like Firefox) "ApplicationDeactivate" prints. Click back on the app, it prints "ApplicationActivate" again, etc. Finally, when you close the app, "ApplicationDeactivate" prints.
This is an interesting idea; if you wanted to determine how much time a user spent using your app, this is one way to do it.
Bookmarks