简体   繁体   中英

Determine source of QKeyEvent

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM