Mouse Hover (Over) Events for Qt Widgets

Posted on Posted in Qt Tutorials, Tutorials

Qt does not have mouse hover, or mouse over (as some people call it) events in its widgets by default but it provides the means to do it quite easily if you just know how to inherit a class and add some protected functions to it. Here is an example that shows how to create a push button (QPushButton) that reacts to mouse hover events.

First, you have to create a class that inherits QPushButton and add the following functions to its protected section of methods and properties:

protected:
void hoverEnter(QHoverEvent *event);
void hoverLeave(QHoverEvent *event);
void hoverMove(QHoverEvent *event);
bool event(QEvent *event);





Next step, you should manually catch QEvent::HoverEnterQEvent::HoverLeave and QEvent::HoverMove events in the event function and return the rest:

switch(event->type())
{
case QEvent::HoverEnter:
hoverEnter(static_cast<QHoverEvent*>(event));
return true;
break;
case QEvent::HoverLeave:
hoverLeave(static_cast<QHoverEvent*>(event));
return true;
break;
case QEvent::HoverMove:
hoverMove(static_cast<QHoverEvent*>(event));
return true;
break;
default:
break;
}
return QWidget::event(event);

Now you can just simply write the contents of what you want to do in the body of hoverEnter, hoverLeave and hoverMove functions.

Download the following complete and simple project that fully demonstrates what is described in this article.

Hover Sensitive Button

Download
Hover Sensitive Push Button Example Project for Qt (4KB ZIP File)




One thought on “Mouse Hover (Over) Events for Qt Widgets

  1. Really Cool for sharing the download! Spent Hours to figure out how to use customised Classes in QT Designer!

Leave a Reply

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