Find which widget had focus when menu item is clicked?



  • After clicking on an item in the application menu, Qt automatically restores focus back to the last active widget. So, for example, if you had a QLineEdit in focus, then click on a menu item, the QLineEdit that was previously in focus will get focus restored after clicking the menu item. It therefore appears that Qt keeps track of the last widget that had focus before a menu item was clicked, and I'm looking for a way to find this widget.

    Is there a function to get which widget had focus before a menu action was performed?



  • @Elsworth55 ,Hi,friends, welcome.

    I found these infomation in qt manual.

    [static] QWidget *QApplication::focusWidget()
    Returns the application widget that has the keyboard input focus, or 0 if no widget in this application has the focus.
    See also QWidget::setFocus(), QWidget::hasFocus(), activeWindow(), and focusChanged().
    

    Try it, maybe it will help you.



  • Thanks for the suggestion. I had tried that function, but when you click on a menu item it gives focus to the menu, so the focusWidget() will be the menu. This therefore can't be used to find out which widget had focus before clicking the menu item.

    The best solution I've come up with is to use the QLineEdit editingFinished() signal and store which QLineEdit last had focus. However, this gets a bit messy due to various reasons, so I was hoping there might just be a function to get the last active widget, but so far I've been unable to find one.



  • @Elsworth55
    This is the function you're looking for.

    QWidget *QWidget::previousInFocusChain() const
    alt text


  • Moderators

    @J.Hilk said in Find which widget had focus when menu item is clicked?:

    QWidget::previousInFocusChain

    I don't think this is what he needs. This one returns the widget which is before the current in the focus chain. It does not have anything to do with the focus history. It is about the focus order (which widget will get focus if you press TAB key).



  • @jsulm said in Find which widget had focus when menu item is clicked?:

    @J.Hilk said in Find which widget had focus when menu item is clicked?:

    QWidget::previousInFocusChain

    I don't think this is what he needs. This one returns the widget which is before the current in the focus chain. It does not have anything to do with the focus history. It is about the focus order (which widget will get focus if you press TAB key).

    oh, seems like my jedi skills are rusty ...



  • Thanks to everyone for the suggestions. I thought I might be overlooking something, but it looks like there is no function to get the last widget in focus.

    I'll just use the editingFinished() signal and store the last QLineEdit that had focus. It's a bit more messy that way, but it should work fine.

    Thanks again.


Log in to reply
 

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