Solved [Ask] What happen if QTimer doesn't stop
-
Hi,
I have a question that: How about memory or something else happen if I start a QTimer but don't stop it.
This is my code:
File a.h
//your code here ```void updateProgressBar() File a.cpp void DivXPlayer::updateProgressBar(){ timer= new QTimer(this); timer->setInterval(1000); timer->setSingleShot(false); connect(timer,SIGNAL(timeout()), myMainUi, SLOT(setProgressBar())); timer->start(); } file c.cpp void call(){ while(1){ updateProgressBar(); } } Thank so much.
-
You are creating new QTimer objects in a tight, unending loop. So, my bet is you're going to run out of memory pretty quickly.
Regarding your question, though: well, if the timer is repeating (and it is), it will continue running and emit "timeout()" signal every second (triggering the setTProgressBar() slot) until you close your application.
-
@Hung-Tran To add to @sierdzio : the timer itself will not consume more memory just because it isn't stopped. But if the slot connected to it allocates memory without freeing it then you will consume more and more memory, but not because of the timer.
-
@jsulm
Connected Slot just set new value for a label and does not allocate anything. So how about memory in this case ? -
@Hung-Tran "So how about memory in this case?" - it was already explained. QTimer itself will not increase its memory consumption if not stopped. But as @sierdzio said: you're creating new QTimers in an endless loop! This will eat up all your memory quite fast, but this is not QTimer issue, but your fault.
-
@Hung-Tran You are allocating memory with this line
timer= new QTimer(this);
Operator "new" is used to allocate memory http://en.cppreference.com/w/cpp/memory/new/operator_new
-
@jsulm I got it. Because the value I want to update is position of a playing clip. So I want to update every second to update progress bar. So do you have solution in my case to update position of clip every second ?
-
@Hung-Tran Thank. I got it.
-
@Hung-Tran said in [Ask] What happen if QTimer doesn't stop:
So do you have solution in my case to update position of clip every second ?
Yes, use QTimer.
-
@Hung-Tran said in [Ask] What happen if QTimer doesn't stop:
So do you have solution in my case to update position of clip every second ?
You already have a soltion:
void DivXPlayer::updateProgressBar(){ timer= new QTimer(this); timer->setInterval(1000); timer->setSingleShot(false); connect(timer,SIGNAL(timeout()), myMainUi, SLOT(setProgressBar())); timer->start(); }
This method is OK. You just need to call it once, not in an endless loop!
And if you want to stop the timer after reaching 100%, either stop it from within setProgressBar(), or add a check for that in your DivXPlayer class, for example.
-
@sierdzio Thank you. I got it. I'll change its behavior in my code.