QTimer - How to work with timer

Introduction:

A timer is a specialized type of clock for measuring time intervals. In the software development, timer is used to call the particular task which needs to run at a specific interval. Timer will independently count the ticks and if it reaches the specified tick value, then it will trigger the event which will be useful for programmer to detect and call the specific functionally to execute. Qt provides a specialized class called QTimer for achieving this concepts.


QTimer:

The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer, connect its timeout() signal to the appropriate slots, and call start(). From then on, it will emit the timeout() signal at constant intervals.

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);

It's good practice to give a parent to your QTimer to use Qt's memory management system. The above code will call the 'update()' function in every 1000ms.

An alternative to using QTimer is to call QObject::startTimer() for your object and reimplement the QObject::timerEvent() event handler in your class (which must inherit QObject). The disadvantage is that timerEvent() does not support such high-level features.

The accuracy of timers depends on the underlying operating system and hardware. Most platforms support a resolution of 1 millisecond, though the accuracy of the timer will not equal this resolution in many real-world situations.

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H


#include <QMainWindow>
#include <QTimer>
#include <QTime>


namespace Ui {
class MainWindow;
}


class MainWindow : public QMainWindow
{
    Q_OBJECT


public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();


private:
    Ui::MainWindow *ui;
    QTimer *timer;


    QTime tt;


public slots:
    void timerUpdate();
};


#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    ui->lblTime->setText(tt.currentTime().toString("hh:mm:ss"));


    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
    timer->start(1000);
}


MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::timerUpdate()
{
    tt.addSecs(1);
    ui->lblTime->setText(tt.currentTime().toString("hh:mm:ss"));
}