Important: Please read the Qt Code of Conduct -

Deferred function call using QTimer.

  • Hi!

    I wrote code to implement a deferred function call using QTimer, but I still have one question: is there a possible error when the program can try to set the _repeat variable to '0' and execute_repeat++ at the same time?

    #include <QTimer>
    #include <iostream>
    #include "preset.h"
    #include "ui_preset.h"
    int _repeat;
    Preset::Preset(QWidget *parent) :
        ui_preset(new Ui::Preset)
        QTimer::singleShot(1000, this, SLOT(repeat_handler()));
        delete ui_preset;
    void Preset::on_comboBox_height_editTextChanged()  // Signal editText changed
    void Preset::delay_function()  // Delay function
        std::cout << "Repeat count: " << _repeat << std::endl;
    void Preset::repeat_handler()  // Repeat handler
        if (_repeat > 0) {  // This is where the global variable checks whether there were calls delay_function
            _repeat = 0;
        QTimer::singleShot(1000, this, SLOT(repeat_handler())); //Re-enabling the timer to cyclical call the function repeat_handler
    void Preset::change_preset_name()  // Call Change preset name
       // Change preset name

  • @Helg1980
    No, signals/slots, timers and input signals all execute in sequence. There are no multiple threads here.

    You don't have to keep invoking QTimer::singleShot(). If you want a regular timer, as your code does, use a repeating QTimer instance.

  • Thanks!
    Used the construction :

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(repeat_handler()));

  • @Helg1980
    This is good.

    If you QTimer *timer = new QTimer() you'll need to delete it when no longer needed/the Preset instance is destructed. If you want one QTimer throughout a Preset, which is what it looks like, you can just have a member QTimer timer (not pointer) and you don't have to worry about leak/scope.

  • Lifetime Qt Champion

    @JonB see:

    @Helg1980 said in Deferred function call using QTimer.:

    QTimer *timer = new QTimer(this);

    The QTimer object has a parent so it will be deleted through the parent child system.

    However, it won't be easily manipulated if that is needed.

  • @SGaist , @Helg1980
    Sorry, you can see from what I wrote I just missed the this parameter. My bad.

Log in to reply