QWheelEvent - can I "hijack" or change the mouse coordinates in the event?



  • I'm sure this will sound like a "why would you want to do that?" question, but in this particular context which I won't waste time describing, it is desired.

    I want to trap the mouseWheelEvent and change the contained mouse coordinates before passing it on to the parent widget.

    sub-classing and implementing mouseWheelEvent isn't the question, rather, simply, how can I modify the cursor coordinates before passing the event along?

    Thanks


  • Moderators

    Why would you want to do that? No, seriously, I'm curious ;)

    As for how - well, one way is to install an event filter on the target object, block the real event and substitute it for your own.
    Something like this:

    bool MyFilterObject::eventFilter(QObject* obj, QEvent* evt)
    {
        if(evt->type() == QEvent::Wheel && !dynamic_cast<MyCustomEvent*>(evt)) { //avoid recursion
            QWheelEvent* whe = static_cast<QWheelEvent*>(evt);
    
            QPointF pt(42.0f, 42.0f);
            QPointF globalPt(42.0f, 42.0f);
            QWheelEvent* myNewEvent = new MyCustomEvent(pt, globalPt, whe); //craft new event
    
            QApplication::instance()->postEvent(obj, myNewEvent); //post it to the receiver
            return true; //block the original
        }
        return false; //pass anything else freely
    }
    

    A thing to note here is that you can't just post another regular wheel event because it would recurse infinitely.
    So one way to solve it is to make your own event type derived from QWheelEvent and check for that. the receiver won't know the difference but you will. It can be a simple copy of the original with only the data you want to change customized:

    struct MyCustomEvent : public QWheelEvent {
        MyCustomEvent(const QPointF& pos, const QPointF& globalPos, QWheelEvent* src): QWheelEvent(
            pos,
            globalPos,
            src->pixelDelta(),
            src->angleDelta(),
            src->delta(),
            src->orientation(),
            src->buttons(),
            src->modifiers(),
            src->phase(),
            src->source()
        ) {}
    };
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.