How can I detect a period of no user interaction?

What you will need to do is use a QTimer [doc.qt.nokia.com] that times out after a number of minutes of no user interaction. Whenever there is user interaction, then you restart the timer. The easiest way to detect any user interaction within an application i.e. mouse clicks(any button), mouse wheel and keystrokes is to install an event filter on the application that listens for these kind of events. For example:

  1. #include <QtGui>
  2.  
  3. class Widget : public QWidget
  4. {
  5.     Q_OBJECT
  6. public:
  7.     Widget()
  8.     {
  9.         timer = new QTimer(this);
  10.         timer->start(4000);
  11.         installEventFilter(this);
  12.         connect(timer, SIGNAL(timeout()), this, SLOT(testSlot()));
  13.     }
  14.     bool eventFilter(QObject *o, QEvent *evt)
  15.     {
  16.         switch(evt->type()) {
  17.         case QEvent::MouseButtonPress:
  18.         case QEvent::MouseButtonRelease:
  19.         case QEvent::Wheel:
  20.         case QEvent::KeyPress:
  21.         case QEvent::KeyRelease:
  22.             timer->start(6000);
  23.             break;
  24.         default:
  25.             break;
  26.         }
  27.         return false;
  28.     }
  29. private:
  30.     QTimer *timer;
  31.  
  32. public slots:
  33.  
  34.     void testSlot()
  35.     {
  36.         qDebug() << "No user interaction";
  37.     }
  38. };
  39. #include "main.moc"
  40.  
  41. int main(int argc, char **argv)
  42. {
  43.     QApplication app(argc, argv);
  44.     Widget box;
  45.     box.resize(100, 200);
  46.     box.show();
  47.     return app.exec();    
  48. }

1 comment

December 5, 2010

Picture of xsacha xsacha

Lab Rat

By the way you can use evt->type() & rather than a switch. But I guess that might be up to preference.

Write a comment

Sorry, you must be logged in to post a comment.