0

I have a Qt application with multiple widgets showing buttons at the same time. In certain circumstances, I want key presses to be sent to one of the widgets, even if that widget doesn't have focus. To do this, I have overridden keyPressEvent() in the master widget (that owns all subwidgets in this application) and re-send the key event to the subwidget if it doesn't have focus using code similar to this:

if (!someWidget->hasFocus())
{
    QApplication::sendEvent(someWidget, keyEvent);
}

This works great as long as someWidget handes said event. If it ignores it, then it enters a nasty infinite recursive loop since events flow up to parents.

Is there a way to know where an event came from so I can prevent this infinite loop? I'm thinking of something like this:

if (!someWidget->hasFocus() && (keyEvent->source != someWidget))
{
    QApplication::sendEvent(someWidget, keyEvent);
}

Or is there a different way I can prevent this from happening?

Jablonski
  • 18,083
  • 2
  • 46
  • 47
KyleL
  • 1,379
  • 2
  • 13
  • 35

1 Answers1

1

When you use signals and slots mechanism you can call sender() which can give you information, but here you can do next: use eventFilter which can give you information about every QObject which sends events to mainWindow, so you can catch event and sender

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
    if(event->type() == QEvent::KeyPress)//your keyPressEvent but with eventFilter
        if(!someWidget->hasFocus() && obj != someWidget)//your focus and source checkings, obj is object which send some event,
                                                        // but eventFilter catch it and you can do something with this info
        {   
        //do something, post event
        }

return QObject::eventFilter(obj, event);
}

Don't forget

protected:
     bool eventFilter(QObject *obj, QEvent *event);

Maybe you need use QKeyEvent, so cast QEvent if you sure that event->type() == QEvent::KeyPress. For example:

QKeyEvent *key = static_cast<QKeyEvent*>(event);
if(key->key() == Qt::Key_0)
{
    //do something
}
Jablonski
  • 18,083
  • 2
  • 46
  • 47
  • It looks like in eventFilter(QObject *obj, QEvent *event), 'obj' is the watched object, not the object that is sending the event. Do you know if there's a way to determine the event origin? – KyleL Sep 23 '14 at 00:07
  • @KyleL what are the circumstances? Do you choose when do this or this is user actions? Maybe you can do this with signals slots and use sender() – Jablonski Sep 23 '14 at 04:33
  • @KyleL and what you want to do? Catch pressing and set text to other textEdits or what? – Jablonski Sep 23 '14 at 04:40