Search code examples
qtqwidgetqmouseevent

QWidget how to detect mouse stop moving


I can do something when mouse is moving by overwriting QWidget's mouseMoveEvent function.

But I want to do something at the moment when mouse stop moving. How can I implement this?


Solution

  • I would recommend using a single-shot QTimer that you restart each time mouseMoveEvent is called. Set the timeout to some threshold of your choosing. For example:

    class Widget : public QWidget
    {
    public:
      Widget(QWidget *parent = nullptr)
        : QWidget(parent)
      {
        setMouseTracking(true);
        mTimer.setInterval(500);
        mTimer.setSingleShot(true);
        connect(&mTimer, &QTimer::timeout, [] {
          qDebug("Mouse stopped moving!!!");
        });
      }
    
      void mouseMoveEvent(QMouseEvent *event) override
      {
        mTimer.start();
      }
    
    private:
      QTimer mTimer;
    };