Reputation: 922
I am trying to show()
a hidden MainWindow from my main.cpp
(in fact all windows are hidden at this point). I tried doing something like this:
QList<QWindow*> windows = QApplication::allWindows();
for (int i = 0; i < windows.size(); ++i) {
if (windows.at(i)->objectName() == "MainWindow")
windows.at(i)->show();
}
But it doesn't work.
In Qt documentation in QApplication::allWidgets()
there is an annotation :
Note: Some of the widgets may be hidden.
As if this function wasn't listing hidden widgets and I suppose that's the same case with allWindows()
, because I tested this piece of code when windows are not hidden and it worked.
Basically in the void MainWindow::closeEvent
function I do:
event->ignore();
hide();
And then I want to be able to reopen the MainWindow when I click on the application's icon.
Does anyone have a better idea how to show a hidden window from main.cpp
or can indicate if I am doing something wrong?
edit: this probably works, my issue lied somewhere totally different.
Upvotes: 0
Views: 743
Reputation: 19122
The method for finding all of a particular kind of window in the Qt Object tree can be shortened:
http://doc.qt.io/qt-5/qobject.html#findChildren
QList <QMainWindow *> mainWindows = qApp->findChildren<QMainWindow *>();
foreach(QMainWindow * w, mainWindows)
{
qDebug() << "Found a main window" << w->objectName()
<< "isVisible?" << w->isVisible();
}
http://doc.qt.io/qt-5/qobject.html#findChild
Or if you know the name of the qobject:
QMainWindow * w = qApp->findChild<QMainWindow *>("My Named MainWindow");
if(w)
{
qDebug() << "Found" << w->objectName() << "isVisible?" << w->isVisible();
}
findChild
and findChildren
can be used on any QObject or a subclass of QObject, and can be used to reflect out a pointer to any of their children.
MyMainWindow * w = qApp->findChild<MyMainWindow *>();
Also if you want any QWidget to not die or close the application if it is the last window to be closed, then use:
w->setAttribute(Qt::WA_DeleteOnClose, false);
http://doc.qt.io/qt-5/qguiapplication.html#quitOnLastWindowClosed-prop
qApp->setQuitOnLastWindowClosed(false);
but then you have to explicitly put qApp->close()
somewhere in your code.
Another related tool to all of this is qobject_cast
; I like using it with QObject::sender();
// some slot connected to by multiple sources
void mySlot()
{
QPushButton * b = qobject_cast<QPushButton *>(QObject::sender());
if(b)
{
qDebug() << "Push Button triggered" << Q_FUNC_INFO;
b->setText("Ouch");
b->setDisabled(true);
}
}
Hope that helps.
Upvotes: 1