Recently, I wanted that QPushButton can emit a signal, when the mouse pointer enters. How can I make it?
I know that QPushButton has some already defin
So QT deal with mouse hovering using the "event" enterEvent (https://doc.qt.io/qt-5/qevent.html look for "QEvent::Enter"). This isn't about the Signal/Slot functionality (https://doc.qt.io/qt-5/signalsandslots.html), this is about Events (https://doc.qt.io/qt-5/eventsandfilters.html) We find enterEvent as a protected method at QWidget class (https://doc.qt.io/qt-5/qwidget.html) which is a base class for QPushButton class (https://doc.qt.io/qt-5/qpushbutton.html).
So what you have to do: to create a new class derived from QPushButton and override the protected method "enterEvent" that QPushButton inherited from QWidget.
Creating the new class:
QT Creator - File - New File or Project...
File and Classes - C++
C++ Class
Choose...
Base class - Custom - QPushButton
Next
define a name for your new class like MyPushButton
In mypushbutton.h:
#ifndef MYPUSHBUTTON_H
#define MYPUSHBUTTON_H
#include
class MyPushButton: public QPushButton
{
Q_OBJECT
public:
using QPushButton::QPushButton; //inherits the QPushButton constructors
signals:
void myPushButtonMouseHover();
protected:
void enterEvent(QEvent *event);
};
#endif // MYPUSHBUTTON_H
In mypushbutton.cpp:
#include "mypushbutton.h"
#include
void MyPushButton::enterEvent(QEvent *event)
{
QMessageBox::warning(this, "Mouse hover", "Mouse hovered MyPushButton"); //popping a message box
emit myPushButtonMouseHover(); //emitting signal
QPushButton::QWidget::enterEvent(event); //calling the "natural" enterEvent
}