I'm developing an application on a small Embedding Linux device with Qt5.5. I need to be able to modify the mouse press coordinates received from Linux ( tslib ) in my application. I've tried implementing an event filter in my main view that modifies the mouse coordinate received, creates a new mouse event and submits the new event to the widget. However, in the widget's mousePressEvent function, I see the debug message only once, and it is for the original coordinates received, not my intercepted and modified coordinate.
Currently, when I touch the screen, I get my debug messages and they look like this:
Mouse Original: QPoint(192,148)
Mouse New: QPoint(128,148)
Mouse Original: QPoint(192,148)
Mouse New: QPoint(128,148)
Mouse Original: QPoint(192,148)
Mouse New: QPoint(128,148)
Mouse Original: QPoint(192,148)
Mouse New: QPoint(128,148)
Mouse Original: QPoint(192,148)
Mouse New: QPoint(128,148)
Mouse Original: QPoint(192,148)
Mouse New: QPoint(128,148)
Mouse Press 192 148
How can I intercept mouse events at the top level, modify their coordinates, and post them to my widget, while also consuming the original mouse events? Thanks!
main.cpp:
MyWidget w;
app.installEventFilter(&w);
w.show();
MyWidget:
bool MyWidget::eventFilter(QObject *object, QEvent *event)
{
if ( event->type() == QEvent::MouseButtonPress ) {
QMouseEvent *orig = static_cast<QMouseEvent*>( event );
QPoint origLocation = orig->pos();
qDebug() << "Mouse Original: "<< origLocation;
int newx = abs(origLocation.x()-320);
QPoint newPoint(newx,origLocation.y());
QMouseEvent *newPosEvent = new QMouseEvent(QEvent::MouseButtonPress, newPoint, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
qDebug() << "Mouse New: " << newPosEvent->pos();
//qApp->postEvent(this, newPos);
return QObject::eventFilter(object, newPosEvent);
}
return QObject::eventFilter(object, event);
}
void MyWidget::mousePressEvent ( QMouseEvent * event )
{
qDebug() << "Mouse Press" << event->x() << event->y();
}
You can "consume" the event and stop its further propagation by returning
true
from theeventFilter()
method. If you don't use an event filter, you can stop the event with itsaccept()
method.You can re-post the event you create using the static method
QCoreApplication::postEvent(obj, evnt);
Also, you might want to intercept the even deeper, for example at
QWindow
level. I mean, if you intercept it at your widget level, and post it to your widget again, it will just get intercepted by the event filter again. You don't post your new event, and you receive the original, because you didn't stop it from propagating.Also, if you want to generate a click, you will have to post two events in a row, a press and and release event: