Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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) :
        QDialog(parent),
        ui_preset(new Ui::Preset)
    {
        ui_preset->setupUi(this);
        QTimer::singleShot(1000, this, SLOT(repeat_handler()));
    }
    
    Preset::~Preset()
    {
        delete ui_preset;
    }
    
    void Preset::on_comboBox_height_editTextChanged()  // Signal editText changed
    {
        delay_function();
    }
    
    void Preset::delay_function()  // Delay function
    {
        _repeat++;
        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;
            change_preset_name();
        };
        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);
    timer->setInterval(1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(repeat_handler()));
    timer->start();
    


  • @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