How to detect user inactivity in Qt?

How can I detect user inactivity in Qt QMainWindow? My idea so far is to have a QTimer that increments a counter, which, if a certain value is passed, blocks the application. Any interaction with the mouse or key should set the timer back to 0. However, I need to know how to properly handle input events that reset; I can reimplement:

virtual void keyPressEvent(QKeyEvent *event)
virtual void keyReleaseEvent(QKeyEvent *event)
virtual void mouseDoubleClickEvent(QMouseEvent *event)
virtual void mouseMoveEvent(QMouseEvent *event)
virtual void mousePressEvent(QMouseEvent *event)
virtual void mouseReleaseEvent(QMouseEvent *event)

... but will the event handlers of all widgets in QMainWindow prevent the events that occur in these controls from reaching QMainWindow? Is there a better architecture for detecting user activity as it is?

+5
source share
2 answers

You can use a custom event filter to handle all keyboard and mouse events received by your application before they are passed to child widgets.

class MyEventFilter : public QObject
{
  Q_OBJECT
protected:
  bool eventFilter(QObject *obj, QEvent *ev)
  {
    if(ev->type() == QEvent::KeyPress || 
       ev->type() == QEvent::MouseMove)
         // now reset your timer, for example
         resetMyTimer();

    return QObject::eventFilter(obj, ev);
  }
}

Then use something like

MyApplication app(argc, argv);
MyEventFilter filter;
app.installEventFilter(&filter);
app.exec();

It definitely works (I tried it myself).

EDIT: And thank you very much ereOn for pointing out that my early decision was not very useful.

+7
source

One of the best approaches is to catch the xidle signal, and then catch so many events from the user. Here you need to capture a QEvent: MouseMove event also

0
source

All Articles