At any time, you can create a QEventLoop object and call exec() on it to start a local event loop. From within the event loop, calling exit() will force exec() to return.从Qt文档上找出这句话。所以,我们时刻都可以为自己的应用程序创建消息循环。看代码吧!
void CDialog::on_pushButton_clicked()//[slot]
{
QDialog tDlg;
tDlg.show();
QEventLoop tLoop;
connect(&tDlg, SIGNAL(finished(int)), &tLoop, SLOT(quit()));
tLoop.exec(QEventLoop::AllEvents);
}
当然,如果没用QEventLoop ,tDlg窗口会一闪而过!
不少人遇到过这个问题:在一个槽函数内创建了一个窗口对象,却没有看到窗口弹出来,或者看到窗口一闪而过。
类似这样:
{void CDialog::on_pushButton_clicked()//[slot]
QDialog dlg;
dlg.show()
}
当然,大家都知道原因:因为到了后面的大括号处,dlg因为出作用域,会被析构掉。解决方法很简单。比如:
将 dlg 作为类的成员,而不是函数的局部变量
将 dlg 前面添加 static,作为静态成员
将 dlg 用 new 分配到 heap 中
...
当然上面的是用 QEventLoop 来解决的。