3

Is there any way to delay proceed of QEvent in Qt?

This pieces of code just show you what I want to do:

QList<QEvent*> waited_events;

...

bool MyQWidget::event(QEvent * event)
{
    if (event->type() == QEvent::KeyPress)
    {
        waited_events.append(event);
        QTimer::singleShot(100, this, SLOT(timer()));  
        return true;
    } else
    return QWidget::event(event);
}

...

void MyQWidget::timer()
{
    if (!waited_actions.isEmpty())
    {
        QEvent* event = waited_events.takeFirst();
        QWidget::event(event);
    }
}

Thanks!

MikhailKrishtop
  • 492
  • 4
  • 17
  • What is not working with this? – Luca Carlon Mar 21 '12 at 19:40
  • 1
    You can use that approach, but you'll have to create a new event. You can use QCoreApplication::postEvent/sendEvent to have it processed. – Frank Osterfeld Mar 21 '12 at 21:34
  • @LucaCarlon This won't work because by the time the `timer()` function gets around to being called, the QEvent* object he saved off will have been destroyed. – Chris Mar 21 '12 at 22:18
  • Okey, can I create new event exactly the same like I already recieve? – MikhailKrishtop Mar 21 '12 at 23:27
  • No, unfortunately `QEvent` does not implement the virtual copy constructor idiom http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8. There's no way to clone an arbitrary QEvent, but you can write a function that clones the ones you're potentially interested in. – Kuba hasn't forgotten Monica Jun 01 '12 at 18:43

1 Answers1

0

As a general rule you do not want to store QEvents that are triggered by QWidgets.

The code snippet that you have posted is correct if you want to delay processing of a QEvent. However, your code snippet will not do what you want because when this:

void MyQWidget::timer()
{
    if (!waited_actions.isEmpty())
    {
        QEvent* event = waited_events.takeFirst();
        QWidget::event(event);
    }
}

gets called your QEvent has already been deleted, so waited_events will always be empty.

If you need MyQWidget to use this approach you'll have to create a new event (like F. Osterfeld suggested). I'm not 100% sure but it looks like you are just trying to catch a QEvent::KeyPress. If that's the case then the simple way is to have MyQWidget override the void QWidget::keyPressEvent(QKeyEvent* event).

LeviX
  • 3,096
  • 3
  • 28
  • 41