How to detect user inactivity in Qt?

末鹿安然 提交于 2019-12-06 02:49:42

问题


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

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 won't the event handlers of all the widgets in the QMainWindow prevent events occurring in those controls from reaching the QMainWindow's? Is there a better architecture for detecting user activity as it is?


回答1:


You could use a custom event filter to process all keyboard and mouse events received by your application before they are passed on to the 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();

This definitely works (I've tried it myself).

EDIT: And many thanks to ereOn for pointing out that my earlier solution was not very useful.




回答2:


One of better approach will be to catch xidle signal rather then catching so many events from user. Here one need to capture QEvent:MouseMove event also



来源:https://stackoverflow.com/questions/3341617/how-to-detect-user-inactivity-in-qt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!