-2

I am making something in QT in C++.

However, when I am using a while(1) loop in the code, the window never appears. I tried many things, such as adding a QApplication::processEvents(); at the end of the loop, but it doesn't work. There is no window.

How do get the window to appear?

Example code:

MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) {
    _ui.setupUi(this);

while(1){
}

}

Thanks

4
  • 1
    You should paste some code so we can see. Commented Jul 30, 2017 at 22:58
  • Adding QMainWindow::show(); before the loop and QApplication::processEvents(); in the loop solves this problem, but the window doesn't close. Commented Jul 30, 2017 at 23:30
  • 3
    This is a perfect example of why you shouldn't block the event loop in a GUI program. Commented Jul 31, 2017 at 0:59
  • 1
    Why do you want to use while(1)? Maybe you can move what's happening in the loop to another thread? Commented Jul 31, 2017 at 8:07

2 Answers 2

3

Every widget constructor should never block the main message loop!

The main message loop looks usually like this:

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    MainWindow w(nullptr);
    w.show();
    int r = a.exec();
    return r
}

In your case your MainWindow ctor never returns, so w.show() is never called and a.exec() (main messgae loop) is never executed.

Not only blocking may be a problem in main window ctor, but also signals that are generated before main message loop is executed gets never raised. For an example establishment of an TCP/IP connection within main window ctor will never raise the connected() signal and associated slots. *1

At least if the creation of the main window is before the main message loop is executed like in 99% the cases.

Sign up to request clarification or add additional context in comments.

Comments

0

You must invalidate the window rectangle and yield so that the paint message is processed; then continue in the while loop; or just code a progress bar window.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.