Using a Timer in Qt

For using the timer in Qt, the class QTimer is intended. First, you need to set the time after which it will trigger. You also need to define a slot that will handle the signal emitted when the timer overflows. Thus, a mandatory condition for using QTimer is the ability to use signals and slots, which means that the class that uses the timer must be a descendant of QObject. Let's create a simple clock as an example.

In the class that is a descendant of QObject (for example, let's use the standard main window class), we declare an instance of QTimer and a slot to handle it:

#include<QTimer>

class MainWindow: public QMainWindow { Q_OBJECT public: QTimer *timer; ...

public slots: //Slot that triggers when the timer overflows void timer_overflow();

...

};

//Include the class to determine the current time #include <QTime>

Next, in the window constructor

 //Display the time value at the start to eliminate the absence of time 
 before the first timer trigger
 ui->label->setText(QTime::currentTime().toString());
 timer = new QTimer;

//Connect the timer overflow signal to the slot QObject::connect(timer,SIGNAL(timeout()), this, SLOT(timer_overflow()));

//Set the timer trigger time (in ms) timer->start(1000); }

//The following method (slot) is called on each timer overflow void MainWindow::timer_overflow() { //Update the time value on the form ui->label->setText(QTime::currentTime().toString()); }

 

As a result, we get a "clock":

screen The project source code can be downloaded here