PDA

View Full Version : Application Lost Focus / Inactive / In Background



javed_alam786
27th April 2011, 12:14
Hi All,

The issue i am facing is basically how do i detect my application has lost focus as a result of user doing something else maybe checking there SMS or making/receiving a call.

All i want to do is detect this focus change and 'Pause' my app from doing any heavy calculation or simply sending a message "User Inactive State" to TCP Server.

Regards,
Javed

Added after 25 minutes:

i have tried these two solutions but none works for me, perhaps i am doing it wrong.

Solution 1:- Does not ssems to be emitting signal when app looses focus.


ProgressWin::ProgressWin(QWidget *parent) : QDialog(parent), ui(new Ui::ProgressWin)
{
ui->setupUi(this);

#ifdef Q_OS_SYMBIAN
this->showMaximized();
#else
this->show();
#endif

QWidget::setFocusPolicy(Qt::StrongFocus);
connect(this, SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(OnAppFocusChanged(QWidget*, QWidget*)));
}


void ProgressWin::OnAppFocusChanged(QWidget* old, QWidget* now)
{
if(NULL == old)
{
// do something or nothing
}
else if(NULL == now)
{
Pause(); // Pause all calculation
SendTCP_UserInActive();
}
else
{
// do something or nothing
}
}




Solution 2 :- Does not work if user selects "Calendar key or Email Key" pressed on Nokia E52 Handset. Its a crappy solution anyway.




void ProgressWin::keyPressEvent(QKeyEvent *e)
{
switch (e->key())
{
case Qt::Key_Calendar:
case Qt::Key_LaunchMail:
case Qt::Key_Menu:
.........
.........
.........
Pause(); // Pause all calculation
SendTCP_UserInActive();
break;
default:
// do something or nothing
}
}

AlexSudnik
27th April 2011, 15:15
QApplication class has a static method : QWidget * QApplication::focusWidget ().

Since it returns 0 if no widget in this application has the focus,it might be useful for what you're trying to achieve.

So your main.cpp might look like this:


QApplication app( argc,argv );

ProgressWin mainWindow;

...

connect( &app , SIGNAL( focusChanged( QWidget*, QWidget* ) ) , &mainWindow , SLOT( OnAppFocusChanged() ) );

...



And then the slot itslef:


void ProgressWin :: OnAppFocusChanged()
{

if( !QApplication::focusWidget() )
{

// pause or whatever action you'd like to perform

}


}

javed_alam786
10th May 2011, 10:08
Hi Alex,

Thanks for the solution. I managed to get it done a different way which works fine according to my need. This solution is open to critisim.

Kind Regards,
Javed

className.h


....
bool eventFilter(QObject *object, QEvent *event);
....


className.cpp


bool ClassName::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn)
{
// pause or whatever action you'd like to perform
}
else if (event->type() == QEvent::FocusOut)
{
// pause or whatever action you'd like to perform
}
else if (event->type() == QEvent::WindowDeactivate)
{
// pause or whatever action you'd like to perform
}
else
{
// pause or whatever action you'd like to perform
}
return false;
}