Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a Qt GUI application has been idle, inside the app itself (Qt)?

Tags:

qt

How to detect when a GUI application has been idle, (ie, no user interaction), for a period of time ?

I have n number of Qt Screens , I want to bring Date-Time screen when application is idle for 5 seconds and when i click on Date-Time screen it should return back to the last screen.

Currently I am using below code, now how to check if system is idle for 5 seconds bring a new form and when some body mousemove/click it should go back to the last form.

CustomEventFilter::CustomEventFilter(QObject *parent) :
    QObject(parent)
{   
    m_timer.setInterval(5000);
    connect(&m_timer,SIGNAL(timeout()),this,SLOT(ResetTimer()));
}

bool CustomEventFilter::eventFilter(QObject *obj, QEvent *ev)
{
    if(ev->type() == QEvent::KeyPress ||
           ev->type() == QEvent::MouseMove)
    {
        ResetTimer();
        return QObject::eventFilter(obj, ev);

     }
    else
    {

    }
}

bool CustomEventFilter::ResetTimer()
{
    m_timer.stop(); // reset timer

}

And my main.cpp looks like this :

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainForm w;
    w.show();
    CustomEventFilter filter;
    a.installEventFilter(&filter);

    return a.exec();


}

Thanks.

like image 560
Bokambo Avatar asked Jun 30 '11 09:06

Bokambo


2 Answers

Override QCoreApplication::notify and a timer on mouse/keyboard events?

(Or just store the time of the event and have a timer check that value periodically, which might be faster than resetting a timer all the time.)

class QMyApplication : public QApplication
{
public:
    QTimer m_timer;

    QMyApplication() {
        m_timer.setInterval(5000);
        connect(&m_timer, SIGNAL(timeout()), this, SLOT(app_idle_for_five_secs());
        m_timer.start();
    }
slots:
    bool app_idle_for_five_secs() {
        m_timer.stop();
        // ...
    }
protected:
    bool QMyApplication::notify ( QObject * receiver, QEvent * event )
    {
        if (event->type == QEvent::MouseMove || event->type == QEvent::KeyPress) {
             m_timer.stop(); // reset timer
             m_timer.start();
        }    
        return QApplicaiton::notify(receiver, event);
    }
};
like image 116
Macke Avatar answered Oct 24 '22 21:10

Macke


According to QT Documentation :

To make your application perform idle processing (i.e. executing a special function whenever there are no pending events), use a QTimer with 0 timeout. More advanced idle processing schemes can be achieved using processEvents().

So you need to create a QTimer with zero timeout interval and connect it to your slot that is called when application is idle.

like image 41
O.C. Avatar answered Oct 24 '22 23:10

O.C.