这是QThread的子类的run方法:Qt的线程和循环问题
void crono::Controller::run() {
//initialise timer
int *i = & this->model->seconds_elapsed;
for (*i = 0; *i < this->model->seconds_total; (*i)++) {
//calculate current seconds/minutes/hours elapsed starting from seconds_elapsed (*i)
this->model->tick();
//should display in the form the time elapsed
this->vista->showTime();
sleep(1000);
}
Beep(1000, 500); //beep when all is over
}
控制器更新模型值。
QT表单在开始时打开,我想在主应用程序线程中。
问题是,对debug * i = 0和seconds_total = X> 0的鄙视,循环只执行一次,在第一次调试停止后(它没有结束),表单弹出但没有任何发生。
我唯一能猜到的是控制器线程失去了优先级,从来没有再次获得CPU。
如何避免这种情况?
编辑 我使用QTimer,与倒霉尝试。
我声明更新为公共时隙,然后这样来实现:
void crono::Controller::update() {
this->modello->tick();
this->vista->showTime();
//eventually stop at some point (pointer to timer and timer->stop()?
//...
//Beep(1000, 500);
}
我插入QTimer在控制器(线程)对象,而不是循环周期:
void crono::Controller::run() {
//inizializzo timer
int *i = & this->modello->secondi_trascorsi;
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),this, SLOT(update()));
timer->start(1000);
}
我不知道为什么,但update()方法永远不会被调用,而不是被称为无限次数。为什么?
不,我不认为这可能是问题。调试或添加一些调试日志记录来检查是否达到睡眠子句。也许其他方法之一导致无限循环? –
“//应该以流逝的时间的形式显示” - 您确定没有直接从线程访问GUI,而是仅通过信号/插槽来访问GUI? – borisbn
我强烈建议保持QThread和实现彼此分离,即不要继承QThread(阅读Zaiborg的链接)。如果你真的重新实现'QThread :: run()',你需要在'run()'方法的末尾调用'exec()',否则任何事件(包括信号)都不会被线程处理。 –