Sumeet Singh Sumeet Singh - 4 years ago 88
C++ Question

What exactly happens with QTimer start function?

I have the following code:

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";

}


and in the main.cpp

#include <QCoreApplication>
#include "mytimer.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

MyTimer mtimer;
qDebug()<<"DONE";

return a.exec();
}


Now the output comes as:

DONE
timer executed
timer executed
...
...
...
...
infinite sequence


I am really confused by this. How is that we are done with our main function and still the code for the
SLOT mySlot()
is getting executed?

What are the important aspects to this? that I need to understand?

Also what changes occurs when I modify mytimer.cpp MyTimer() to:

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();
}


There is one timer executed just before DONE is printed. To Be specific the output now becomes:

timer executed
DONE
timer executed
timer executed
...
...
...
...
infinite sequence


What caused that separate timer executed to appear above the DONE?

Answer Source

No - your main function is not done. It called a.exec() which will never return in your application.

a.exec() in turn processes a "message queue" which triggers all the timer events that call mySlot().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download