Evgenii Legotckoi
Evgenii LegotckoiAug. 20, 2015, 8:45 a.m.

Qt/C++ - Lesson 009. QTimer – How to work with timer?

Let's talk a bit about using the QTimer class in Qt. This is a small light topic after a series of lengthy articles on QSqlTabelModel and its consequences. And then already at the very gray matter boils.

We may need timers to poll devices over a LAN via the TCP / IP stack at regular intervals, or to check data hourly or active connections to the server. For anything !? And here QTimer comes to our rescue, which We will consider using the example of every second output of time in QLabel.

The program code was written in QtCreator 3.3.1 based on Qt 5.4.1.

Project structure for QTimer

We use a minimum of files in our project:

  • QDataMapperWidget.pro - profile;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - window source code;
  • main.cpp - the main source file from which the application starts;
  • mainwindow.ui - form of the main application window;
  • And we will draw the shape in the QtCreator Designer. However, there is nothing to draw. Throw the QLabel in the middle and you're done.

mainwindow.h

All we need to be happy in this project is a slot that will react to the triggering of a QTimer, and the object of this class itself.

#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 */
    QTimer *timer;
};

#endif // MAINWINDOW_H

mainwindow.cpp

And now a few lines to start the timer. In my opinion, there are more comments than code. Usually they write this way on Assembler - 20% of the code and 80% of the comments.

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    /* Немножко подшаманим QLabel, чтобы он был больше,
     * и заметнее в пустующем окне
     * */
    QFont font("Times", 28, QFont::Bold);
    ui->label->setFont(font);

    /* При первом запуске приложения поместим текущее время в QLabel
     * */
    ui->label->setText(QTime::currentTime().toString("hh:mm:ss"));

    /* Инициализируем Таймер и подключим его к слоту,
     * который будет обрабатывать timeout() таймера
     * */
    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(slotTimerAlarm()));
    timer->start(1000); // И запустим таймер
}

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

/* Слот для обработки timeout() таймера
 * */
void MainWindow::slotTimerAlarm()
{
    /* Ежесекундно обновляем данные по текущему времени
     * Перезапускать таймер не требуется
     * */
    ui->label->setText(QTime::currentTime().toString("hh:mm:ss"));
}

Outcome

As a result, at startup, we will find out how the time in the application window changes every second.

QTimer example

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

N
  • Aug. 8, 2017, 6:03 a.m.

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

void MyServer::slotWriteClient()
{
    if(lis.length() != 0)
    {
        QString str;


        for(int i = 0; i < lis.length(); i++)
        {
            socet = lis.at(i);
            if(lineEdit_4->text() == NULL){
                str = QString::number(i + 1) + " Client";
                sendToClient(socet,
                             "Server Response: Received \"" + str + "\""
                             );
            }
            else
            {
                str = lineEdit_4->text();
                
                if(i >= 1)
                {    

                    socn = i;
//                    QTimer *timer = new QTimer(this);
//                    timer->setInterval(2000);
//                    connect(timer, SIGNAL(timeout()), this, SLOT(slotZad(i)));

//                    timer->start();
                    QTimer::singleShot(2000, this, SLOT(slotZad()));

                }
                else
                    sendToClient(socet, str);
            }
        }
    }
    else
        m_ptxt->append("Пуст");
}

void MyServer::slotZad()
{
    QString str;

    qDebug() << socn;
    socet = lis.at(socn);
    str = lineEdit_4->text();
    sendToClient(socet, str);
}
Evgenii Legotckoi
  • Aug. 8, 2017, 6:35 a.m.
Добрый день!
Цикл for успевает отработать и сформировать переменную socn до того, как слот slotZad отработает хотя бы раз. При этом цикл for выполнится полностью. В результате в переменной socn будет использоваться переменная i равная последнему индексу.
Вам нужно переделать участок с QTimer::singleShot как-то иначе, например, прерывать цикл for, как только запустили QTimer::singleShot. А в слоте slotZad() инкрементировать переменную socn с проверкой на выход за пределы списка сокетов. И если есть ещё не обработанные сокеты, то запускать заново QTimer::singleShot в слоте slotZad().

Дополнительное code review:
Вместо этого
if(lineEdit_4->text() == NULL){
используйте метод QString::isEmpty()
if(lineEdit_4->text().isEmpty()){

P/S/ В дальнейшем создавайте темы с подобными вопросами на форуме сайта. Вопрос, конечно, имеет отношение к статье, но косвенное.

N
  • Aug. 8, 2017, 7:30 a.m.

Спасибо! Учту.

AC
  • Sept. 6, 2022, 3:40 p.m.

Вижу вы используете
new QTimer();
А кто будет память освобождать?
Почему вы вообще используете указатель QTimer *timer; а не объявите поле QTimer timer;?

Evgenii Legotckoi
  • Sept. 7, 2022, 3:16 a.m.
  • (edited)

Потому что 7 лет назад я был бестолковее, чем сейчас.

f
  • Sept. 7, 2022, 11 p.m.

QTimer унаследован от QObject и ему передан this, идиома Qt предпологает что при вызове деструктора обьекта класса MyServer, обьект *timer тоже будет освобожден. Поправьте если ошибаюсь!

Evgenii Legotckoi
  • Sept. 12, 2022, 3:04 a.m.

Да, именно так. Но в коде без this написано - это ошибка в статье.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
MB

Qt - Test 001. Signals and slots

  • Result:57points,
  • Rating points-2
MB

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
GK

C++ - Test 005. Structures and Classes

  • Result:0points,
  • Rating points-10
Last comments
J
JonnyJoJune 9, 2023, 12:14 a.m.
Qt/C++ - Lesson 019. How to paint triangle in Qt5. Positioning shapes in QGraphicsScene Евгений, здравствуйте! Решил поэкспериментировать немного с кодом из этого урока, нарисовать вместо треугольника квадрат и разобраться с координатами. В итоге, запутался. И ни документация,…
J
JonnyJoMay 26, 2023, 2:24 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 4:49 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
J
JonnyJoMay 21, 2023, 10:49 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 5:57 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
Now discuss on the forum
T
TwangerJune 7, 2023, 11:12 p.m.
Ошибка при выполнении триггерной функции (GreenPlum) Есть 3 таблицы fact_amount со структурой: CREATE TABLE fact_amount ( id serial4 NOT NULL, fdate date NULL, type_activity_id int4 NULL, status_id int4 NULL, CONSTRAINT fact…
AR
Alexander RyabikovJune 7, 2023, 1:35 a.m.
Работа с QFileSystemModel Вопросик по теме QFileSystemModel в Linux. Он, как и положено, обновляется самостоятельно, если директория локальная. Но, вот, сетевая папка (у меня шара samba) не обновляется. Как её можно…
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 4:07 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
АБ
Алексей БобровDec. 15, 2021, 8:03 a.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …

Follow us in social networks