I need to get mouse movement inside of a widget:
An eventFilter is not possible, since that would be installed on the QApplication. The widget is far down in the type hierarchy. Passing this widget up to the main function where the QApplication object is created would mess up the code.
Therefore I implemented
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent *event);
in the widget.
None of the events is called. Even after setting mousetracking to true on both the central widget and the widget where I actually need the event, the functions are not called:
centralWidget->setMouseTracking(true);
How do you get mouse events in Qt for custom subclass of QWidget ?
Update: here is the .h file:
class Plot : public QWidget
{
Q_OBJECT
//...
protected:
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent *event);
Update:
I tried the eventFilter approach.
in the .h file:
protected:
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent * event);
void mouseMoveEvent(QMouseEvent *event);
bool eventFilter(QObject* object, QEvent* event);
in the .cpp :
void Plot::mousePressEvent(QMouseEvent *event){
//...
}
void Plot::mouseMoveEvent(QMouseEvent *event){
}
void Plot::mouseReleaseEvent(QMouseEvent *event){
}
bool Plot::eventFilter(QObject* object, QEvent* event)
{
if(event->type() == QEvent::MouseButtonPress)
{
QMouseEvent* mev=static_cast<QMouseEvent*>(event);
qDebug()<<mev->x();
}
return false;
}
Then in the constructor of my qWidget:
this->installEventFilter(this);
The code compiles and runs fine. Breakpoints at the if statement in the event filter stop the program, the eventFilter method is called. But the if statement is never evaluated to true. Even the simple buttonPress events are not registered.
The overwritten methods for the events are still not called.
QObject
: doc.qt.io/qt-5/qobject.html#installEventFilter. There would be no need to move the object to the application's scope. – Nicolas Holthaus