Getting MouseMoveEvents in Qt

后端 未结 2 1129
攒了一身酷
攒了一身酷 2020-12-09 02:15

In my program, I\'d like to have mouseMoveEvent(QMouseEvent* event) called whenever the mouse moves (even when it\'s over another window).

Right now, in my mainwindo

相关标签:
2条回答
  • 2020-12-09 02:26

    I had the same problem, further exacerbated by the fact that I was trying to call this->update() to repaint the window on a mouse move and nothing would happen.

    You can avoid having to create the event filter by calling setMouseTracking(true) as @Kyberias noted. However, this must be done on the viewport, not your main window itself. (Same goes for update).

    So in your constructor you can add a line this->viewport()->setMouseTracking(true) and then override mouseMoveEvent rather than creating this filter and installing it.

    0 讨论(0)
  • 2020-12-09 02:36

    You can use an event filter on the application.

    Define and implement bool MainWindow::eventFilter(QObject*, QEvent*). For example

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
      if (event->type() == QEvent::MouseMove)
      {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        statusBar()->showMessage(QString("Mouse move (%1,%2)").arg(mouseEvent->pos().x()).arg(mouseEvent->pos().y()));
      }
      return false;
    }
    

    Install the event filter when the MainWindows is constructed (or somewhere else). For example

    MainWindow::MainWindow(...)
    {
      ...
      qApp->installEventFilter(this);
      ...
    }
    
    0 讨论(0)
提交回复
热议问题