本文介绍了如何在Qt中检测用户不活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Qt QMainWindow中检测用户不活动?到目前为止,我的想法是让QTimer递增一个计数器,如果传递了某个值,该计数器将锁定应用程序.任何鼠标或按键的交互都应将计时器设置回0.我可以重新实现:

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)

...但是QMainWindow中所有小部件的事件处理程序不会阻止那些控件中发生的事件到达QMainWindow的事件吗?是否有更好的体系结构可以检测用户活动本身?

...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?

推荐答案

您可以使用自定义事件过滤器来处理应用程序接收到的所有键盘和鼠标事件,然后再将它们传递给子窗口小部件.

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);
  }
}

然后使用类似的东西

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

这绝对有效(我自己尝试过).

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

非常感谢ereOn指出我以前的解决方案不是很有用.

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

这篇关于如何在Qt中检测用户不活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 23:52