在Qt中,经常碰到关闭窗口之后,程序中的循环依旧运行。查资料知道跟线程和进程有关系,比较麻烦,以后再慢慢看线程和进程知识。今天想到一个比较偷懒的方法,具体方法如下(部分代码):
1 在类中设立判断循环的标志:isLooopFlag,以及槽函数stopLoop。
Update::Update(QWidget *parent) :
QDialog(parent),
ui(new Ui::Update)
{
ui->setupUi(this);
QTextCursor textCursor=ui->textEdit->textCursor();
textCursor.movePosition(QTextCursor::End);
ui->textEdit->setTextCursor(textCursor);
isLoopFlag=true;
}
void Update::stopLoop()
{
qDebug()<<"stopLoop";
isLoopFlag=false;
}
然后在循环中加入判断, 如果isLoopFlag为false,则结束循环。最后在main函数中将lastWindowClosed信号和槽函数stopLoop连接起来。
if(!isLoopFlag)
break;
int main(int argc,char**argv)
{
QApplication app(argc,argv);
Update *updateDialog=new Update;
//app.setMainWidget(updateDialog);
updateDialog->show();
app.connect(&app,SIGNAL(lastWindowClosed()),updateDialog,SLOT(stopLoop())); //将lastWindowwClosed()信号与stopLoop连接起来
int result=app.exec();
qDebug()<<result;
delete updateDialog;
return result;
}
当然,这只是比较歪门邪道的方法。涉及到线程和进程肯定还有更标准的方法。