我有以下代码:
mytimer.cpp
#include "mytimer.h"
#include <QtCore>
MyTimer::MyTimer()
{
timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(mySlot()));
timer->start(1000);
}
void MyTimer::mySlot()
{
qDebug()<<"timer executed";
}
并且在 main.cpp
#include <QCoreApplication>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyTimer mtimer;
qDebug()<<"DONE";
return a.exec();
}
现在输出如下:
DONE
timer executed
timer executed
...
...
...
...
infinite sequence
我真的很困惑。我们如何完成我们的 main 函数并且仍然执行 SLOT mySlot()
的代码?
这有哪些重要方面?我需要了解什么?
另外,当我将 mytimer.cpp MyTimer() 修改为:
时会发生什么变化:MyTimer::MyTimer()
{
timer = new QTimer(this);
QEventLoop eventloop;
connect(timer,SIGNAL(timeout()),this,SLOT(mySlot()));
connect(timer,SIGNAL(timeout()),&eventloop,SLOT(quit()));
timer->start(1000);
eventloop.exec();
}
在打印DONE 之前有一个计时器执行。具体来说,输出现在变为:
timer executed
DONE
timer executed
timer executed
...
...
...
...
infinite sequence
是什么导致那个单独的timer executed 出现在DONE 之上?
最佳答案
否 - 您的主要功能尚未完成。它调用了 a.exec(),它永远不会在您的应用程序中返回。
a.exec() 依次处理一个“消息队列”,它触发所有调用 mySlot() 的定时器事件。
关于c++ - QTimer 启动函数到底发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42051724/