PDA

View Full Version : QTimer Usage in C++ Unix / Windows



rcanerA
12th May 2017, 18:46
Hello everyone,

This is a basic issue, but i didnt understand why I am failed timer slots. I used Qt 5.7 in console application timer isn't fired timeout signal.



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

MyTimer* myTimer = new MyTimer();

while(true)
{
QThread::yieldCurrentThread();
}

return a.exec();
}


#ifndef MYTIMER_H
#define MYTIMER_H

#include <QObject>
#include <QTimer>
class MyTimer : public QObject
{
Q_OBJECT
public:
explicit MyTimer(QObject *parent = 0);
QTimer* timerObj;
signals:

public slots:
void TimerTick();
};

#endif // MYTIMER_H

#include "mytimer.h"
#include "iostream"
MyTimer::MyTimer(QObject *parent) : QObject(parent)
{
timerObj = new QTimer(this);
timerObj->setInterval(1000);
connect(timerObj,SIGNAL(timeout()),this,SLOT(Timer Tick()));
timerObj->start();
}

void MyTimer::TimerTick()
{
std::cout << "Timer Interrupt" << std::endl;
}

d_stranz
12th May 2017, 20:49
Your timer does not start running until you call QApplication::exec() (line 15 in your main.cpp) because timers need an event loop and the event loop isn't started until exec() is called. Your infinite while() loop prevents this from ever happening.

rcanerA
12th May 2017, 21:38
Thanks it is working now however i dont understand totally. a.exec() is used for what ?

This exec() is like as a thread run function. Am I right?

And also when I dont use QCoreApplication, can timer work anyway?
I mean QCoreApplication a(argc,argv) and a.exec() removed from the main. Rest of the code will be same.

d_stranz
13th May 2017, 19:56
And also when I dont use QCoreApplication, can timer work anyway?

No. QApplication is what runs the event loop, and everything in Qt depends on an active event loop. You cannot have a Qt app without a QApplication class and exec().

rcanerA
15th May 2017, 05:53
Thnak you so much.