Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
237 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...