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 repeatingQTimer
instance. -
@Helg1980
This is good.If you
QTimer *timer = new QTimer()
you'll need todelete
it when no longer needed/thePreset
instance is destructed. If you want oneQTimer
throughout aPreset
, which is what it looks like, you can just have a memberQTimer timer
(not pointer) and you don't have to worry about leak/scope. -
@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.