Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

c++ - Window doesn't appear when using while loop

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...