How do I implement QHoverEvent in Qt?


I'm just learning Qt with C++. I have successfully implemented signals and slots to trap standard events like ButtonPushed(), etc. However, I want to have a function called when I mouse over and mouse out of a QLabel. It looks like QHoverEvent will do what I need, but I can't seem to find any tutorials or examples on how to implement this. Is it done the same way as signals and slots?. I tried:

connect(ui.lbl_test, SIGNAL(QHoverEvent), this, SLOT(TestFunc(QEvent::Type type, const QPoint & pos, const QPoint & oldPos)));

.. but the function didn't get called when I hovered over the label.

Here is the function, listed in the header file as a public slot:

void MyDialog::TestFunc(QEvent::Type type, const QPoint & pos, const QPoint & oldPos) {
     QMessageBox::information(this, tr("Hey"), tr("Listen!"));

Can anyone help me figure this out or point me to a good example?


After reading a post below, I found no setFlag() member to call for my label widget, but I did try:

    connect(ui.lbl_test, SIGNAL(ui.lbl_test->mouseMoveEvent()), this, SLOT(TestFunc(QMouseEvent *event)));

And updated TestFunc() accordingly. But still nothing happens when I mouse over.

After looking I am not sure QLabel even inherits the mouseMoveEvent() even from QWidget. If this is true, is there a widget that does, or a list of objects that inherit it somewhere?. All I can tell from the documentation on their site is how many inherited functions an object has..

4/19/2016 5:29:36 PM

Accepted Answer

Using signals and slots for this purpose isn't going to work.

mouseMoveEvent() is not a signal or meta-method and cannot be connected to a slot.

Subclassing the widget class and overriding mouseMoveEvent() will allow you to get mouse-move-events, but that is a very heavyweight way to accomplish this (and adds one more class to your source base).

Instead, consider implementing an eventFilter() method on your MyDialog class and installing it on the QLabel. With this event filter method, you can intercept all the events for a given QObject instance.

Here is the documentation on Event Filters.

Additionally, through looking at the code sample, I'd recommend you take a moment to investigate what the SIGNAL() and SLOT() macros do. You can see how they are defined in $QTDIR/src/corelib/kernel/qobjectdefs.h

10/22/2015 8:26:18 PM

According to the document link you give you're only going to get this QHoverEvent if your widget has the Qt::WA_Hover flag.

After constructing the widget call:


and see if it works.

Another way of achieving the same result is to override mouseMoveEvent() in your widget
notice that this function too will not be normally called unless you call:


This is basically how QT implements the hover event internally.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow