Focus to previous application after closing a dialog

  • Hello,

    I am working on a Qt app which is used with a hardware controller. I want to launch a frameless dialog box with keyboard input allowed when a button is clicked on the hardware and when I close the dialog, I want to return the focus back to where it was before. I have tried a few things but the only behaviour I am able to achieve is using QDialog::raise() which activates my application window and when I close the dialog box, it returns the focus to my application. I was wondering if there's a way around for this so that I can open the dialog without activating the app window and close the dialog and give the focus to where ever it was prior to opening the dialog.

    Any help is appreciated.

  • Lifetime Qt Champion


    You might be able to use focusObject for that purpose.

    Hope it helps

  • @SGaist I am not exactly sure how this would help? I wanna launch a dialog just "Spotlight" on OSX. After opening it, it gets the key focus and after I am done, it restores the keyboard focus to the previously active position.

  • Lifetime Qt Champion

    You can get the object that has the focus before calling your dialog and once it's done you set the focus on that object again.

  • @SGaist I thought it was only specific to the Qt application and not global. Another question, how do I set focus to a QObject? Casting it to a QWidget crashes my app for some reason.

  • @SGaist I think it actually does what I thought. It returns a null value if my app is currently not in focus and returns an object when my app is in focus.

  • Lifetime Qt Champion

    Where are you calling that dialog from ?

  • @SGaist I have a hardware controller which send an event which in turn emits a signal to trigger the dialog pop up.

  • Qt Champions 2017

    Hi you can maybe get the wanted effect with

    MainWindow::MainWindow(QWidget* parent) :
      ui(new Ui::MainWindow) {
      QTimer::singleShot(5000, [ = ] {
        Dialog d;

    alt text

  • @mrjj Hi, in your example, I want the keyboard focus to be in the new dialog that popped up and when you close it, it should return the keyboard focus to your previous focussed application.

  • Qt Champions 2017

    ok so not your own app
    but any other random application running on the OS
    that might have had the keyboard focus.

    I don't think Qt provide a way for that.
    Seems very platform specific.

  • @mrjj Yea seems like that's the case

  • Qt Champions 2017

    You should then look at the native api to see
    how to enumerated running "windows"

    Can I ask why you need such unusual behavior ?

Log in to reply

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