2
votes

I have the following problem with the test Qt application, which contains one parent widget and two child widgets, which are separate windows. If the parent widget is hidden, then closing a single child widget implies closing the second child as well as closing the whole application.

Is it the normal behavior of the parent/child widgets in Qt? Is there a way to keep the second child widget visible and the application running?

#include <QApplication>
#include <QtWidgets>

class MyWidget : public QWidget {
public:
    MyWidget(const QString& title = "", QWidget *parent = nullptr) :
        QWidget(parent) {
        setWindowTitle(title);
        setWindowFlags(windowFlags() | Qt::Window);
        setVisible(true);        
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyWidget parent("Parent");
    MyWidget *child1 = new MyWidget("Child1", &parent);
    MyWidget *child2 = new MyWidget("Child2", &parent);
    QTimer::singleShot(5000, [&](){parent.hide();});

    return a.exec();
}

There're three widgets of simple class MyWidget: the parent one 'parent' with two childs 'child1' and 'child2'. After 5 sec the parent widget is hidden by the QTimer::singleShot. After that, if I close, e.g. child1 window, the second window child2 is also automatically closed and the application is finished.

I'd expect that child1 and child2 are independent, and closing one of them shouldn't close another one.

1

1 Answers

2
votes

Usually children in Qt are independant of another just like you want them to. However when the last primary window is closed in (see QApplication::lastWindowClosed) the application closes as a whole. Likely thats whats happening here. I am unsure why, though.

What you could try is manually define closeEvents for your windows. Still your behaviour is weird, as I remember reading that hiding a parent window should also hide its children here: (https://www.qtcentre.org/threads/61708-Multiple-windows-hide-parent-when-child-shown-unhide-when-child-closed).