Stan
Stan

Reputation: 13

How to manage another window in Qt?

This simplified C++ source code shows the problem. There is a main window for some GUI operations having a Start button initiating another window in a function. It is required to show this window until user's exit, like the main one. Is this possible to apply exec() function in a similar way? Hopefully, without any class definitions and header files. Using sleep(), as below, is not a good solution. And without this the window quickly disappears.

#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QPushButton>
#include <QThread>

void next()
{
    QMainWindow nextWin;
    nextWin.show();
    QThread::sleep(10);
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QMainWindow mainWin;
    QPushButton *Start = new QPushButton;
    Start->setText("Start");
    mainWin.setCentralWidget(Start);
    mainWin.setGeometry(300,200,100,100);
    mainWin.show();
    QObject::connect(Start, &QPushButton::clicked, next);
    return a.exec();
}

Upvotes: 1

Views: 241

Answers (1)

Meliodas
Meliodas

Reputation: 337

You could create the window on the heap, and let it delete itself when it is closed:

void next()
{
    QMainWindow* nextWin = new QMainWindow();
    nextWin->setAttribute(Qt::WA_DeleteOnClose);
    nextWin->show();
}

But, I don't think you should have multiple main windows in your application. Use QDialog or QWidget instead.

void next()
{
    QDialog nextWin;
    nextWin.exec();
}

Upvotes: 2

Related Questions