Solution: Qt setMouseTracking Doesn’t Work

By default, Qt will set any QWidget into a QMainWindow unless you set it yourself. This is possibly why you can’t setMouseTracking in your default QWidget. You need to enable setMouseTracking if you want real-time mouse position tracking; it is disabled by default. This is how I got it to work:

MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent),
    ui(new Qt::MainWindow)
{

   ui->setupUI(this);

   this->setMouseTracking(true);
   ui->centralWidget->setMouseTracking(true);

}

If you were working on a custom widget and later instantiated as a child, then this->setMouseTracking should work. Note, it is redundant to set it twice, but you must do it this way. I’ve tested it and it doesn’t work without the other.

To see an example of a functioning implementation, take a look at my Overriding QWidget Events tutorial.

This entry was posted in Qt and tagged , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *