Important: Please read the Qt Code of Conduct -

How to get main window from dialog?

  • Hi!

    I have a dialog with a buttonbox, OK and Cancel, and I want the OK-button to change the index of my Stacked Widget that is placed in my main window. How do I get the main window from my dialog?


  • The correct way would be to make the dialog emit a signal and let the main window take care of changing the index.

    anyway if you passed the mainwindow as parent in the constructor dialog you could get it via qobject_cast<MainWindowType*>(parent()) method

  • Moderators

    As @VRonin said you can retrieve it from the QObject parent property. However for the sake of design, you shouldn't do it in the first place. As he hinted, the QDialog should know nothing of the outside world (consequently of the MainWindow) it should rather "notify" others of things that happened (with signals).

    This way you also ensure you can use your dialog with a QWidget parent, of with QLineEdit parent etc., which is not true if the dialog knows it's owned by a QMainWindow object.
    Kind regards.

Log in to reply