Few talk about the use of class QTimer in Qt. This is a small lightweight theme after a series of articles about QSqlTabelModel volume and the resulting consequences of it.
Timers we may need to create a poll LAN devices via TCP / IP stack with certain intervals or hourly data validation or active connections to the server. Yes to anything !? And here we come to the aid QTimer, which we consider the example of output every second time QLabel.
Project structure
We use a minimum of files in our project:
- QDataMapperWidget.pro
- mainwindow.h - header file of the main application window;
- mainwindow.cpp -source window;
- main.cpp - the main source file from which the application starts;
- mainwindow.ui - form of the main application window;
A draw form in the Designer Qt Creator. But there is nothing to draw. QLabel thrown into the middle and ready.
mainwindow.h
All we need to be happy in this project - a slot that will respond to the operation of a QTimer, but the object of this class.
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFont> #include <QTimer> #include <QTime> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void slotTimerAlarm(); private: Ui::MainWindow *ui; QTimer *timer; }; #endif // MAINWINDOW_H
mainwindow.cpp
And now a few lines to launch the timer. In my comments more than code. Usually so on Assembler`e write - 20% and 80% of the code comments.
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); /* Slightly change a QLabel, that it was more and more noticeable * in an empty box * */ QFont font("Times", 28, QFont::Bold); ui->label->setFont(font); /* When you first launch the app put the current time in QLabel * */ ui->label->setText(QTime::currentTime().toString("hh:mm:ss")); /* Initialize the timer and connect it to the slot, * which will handle the timeout () timer * */ timer = new QTimer(); connect(timer, SIGNAL(timeout()), this, SLOT(slotTimerAlarm())); timer->start(1000); // И запустим таймер } MainWindow::~MainWindow() { delete ui; } /* Slot processing timeout () timer * */ void MainWindow::slotTimerAlarm() { /* Every second update data on the current time * Restart timer is not required * */ ui->label->setText(QTime::currentTime().toString("hh:mm:ss")); }
Conclusion
As a result, when you start to discover how every moment in time is changing us in the application window

Добрый день! Появилась проблемка. Есть клиент-серверное приложение. Нужно послать с сервера к клиентам сообщение через определенные промежутки времени. Реализовал это таким образом, что если у нас в QList лежит больше 1 сокета, то сначало посылается сообщение 1 клиенту, а потом включается таймер, но перед этим записывалось значение i в глобальную переменну(i взято из for). Использовал QTimer::singleshot(2000,this,Slot(slotZ()));. происходит вызов другой функции, где значение сокета берется из списка, по номеру как раз взятого из глобальной переменны, но почему то заместо того чтобы послать на 2 и 3 клиент через 2 сек сообщение, он посылает 2 сообщения на последний клиент.
Спасибо! Учту.