Wait on event



  • Hi,

    I want to create delay of 25 seconds (random value) for syncing purpose.

    But at the same, I dont want UI to get blocked for 25 seconds, it should end the sleep as soon as user operates. For example, mousePress event.

    Is there any implementation present by default in Qt?

    Like, waitForEvent..

    Thanks,
    Kumara


  • Moderators

    @kumararajas

    qApp->installEventFilter( fitlerObject );
    

    Then you can inspect every event before it is sent to the receiver object.
    So in there check for mouse button press events for example. Bbut don't return true if you like the event to be delivered to the receiver object, like in every other event-filter method implementation.


  • Qt Champions 2016

    @kumararajas

    class EventWaiter : public QObject
    {
        Q_OBJECT
    
         static const int timeout = 25000; // 25 secs
    
    public:
        EventWaiter()
        {
            qApp->installEventFilter(this); //< This is discouraged, use at your own risk
        }
    
        ~EventWaiter()
        {
            qApp->removeEventFilter(this);
        }
    
        bool eventFilter(QObject * watched, QEvent * event) override
        {
            Q_UNUSED(watched);
            switch(event->type())
            {
            case QEvent::MouseMove:
            case QEvent::MouseButtonPress:
            // ... more events ...
                emit eventCaptured();
                // Fallthrough!
            default:
                return false;
            }
        }
    
        void waitForEvents()
        {
            QObject::connect(this, &EventWaiter::eventCaptured, &loop, &QEventLoop::quit);
            QTimer::singleShot(timeout, &loop, &QEventLoop::quit);
            loop.exec(); //< This is discouraged, use at your own risk
        }
    
    signals:
        void eventCaptured();
    
    private:
        QEventLoop loop;
    };
    

    Use as:

    EventWaiter waiter;
    waiter.waitForEvents();
    


  • Thanks for the details! Above answers, makes sense for me!

    Thank you again!

    Kumara


  • Moderators

    @kumararajas
    an alternative (to avoid the event filter) would be to subclass QApplication and override the notify() method. Every event is routed through this method. Thus you do not introduce any extra overhead.
    But anyway the event-filter approach IMO has hardly any noticeable performance impact.



  • @raven-worx This is kinda cool! Thanks for the idea. I am going to try this as well.
    I will keep the results posted. here.

    Thanks!


Log in to reply
 

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