Get MainWindow in Qt Widgets

Update 2017/04/27 (thanks to grholk!):

The proper way would not be to check the objectName, which can change at any time, but rather to check if the widget is an instance of QMainWindow. Take advantage of what Qt makes available by using a foreach.

QMainWindow* getMainWindow()
{
    foreach(QWidget *widget, qApp->topLevelWidgets())
        if (QMainWindow *mainWindow = qobject_cast(widget))
            return mainWindow;
    return NULL;
}

Old version:

Provided how much you can do with Qt Widgets, or Qt in general, it’s no surprise that such “specialized” function is not present (the QApplication::activeWindow() does not make it, as the window might not be active).

#include <QApplication>
#include <QDateTime>

QMainWindow* getMainWindow()
{
    QWidgetList widgets = qApp->topLevelWidgets();
    for (QWidgetList::iterator i = widgets.begin(); i != widgets.end(); ++i)
        if ((*i)->objectName() == "MainWindow")
            return (QMainWindow*) (*i);
    return NULL;
}

If, for whatever reason, you changed the “objectName” property of the main window, update the above if with this name.

4 responses to “Get MainWindow in Qt Widgets

  1. The proper way would not be to check the objectName, which can change at any time, but rather to check if the widget is an instance of QMainWindow. Also, you are reinventing the wheel with your loop. Take advantage of what Qt makes available by using a foreach. Here’s a better version of your function:

    #include

    QMainWindow* getMainWindow()
    {
    foreach(QWidget *widget, qApp->topLevelWidgets())
    {
    if (QMainWindow *mainWindow = qobject_cast(widget))
    {
    return mainWindow;
    }
    }
    return NULL;
    }

    More readable, more concise, and you don’t have to go faffing around changing it every time your QMainWindow’s objectName gets updated.

  2. 1maluquinho dis8£:Calma&#s230;vÃeo fazer um acordão com Tio San ( Defesa e Reciprocidade) comprar SH com tudo que tem direito e fabricados aqui e ainda de lambuja vamos comprar a Saab…O GRIPEN NG É NOSSO

Leave a comment