简体   繁体   中英

What happen if QTimer doesn't stop

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 ah

void updateProgressBar()

File a.cpp

void updateProgressBar(){
timer= new QTimer(this);
timer->setInterval(1000);
timer->setSingleShot(false);
connect(timer,SIGNAL(timeout()),
        myMainUi,
        SLOT(setProgressBar()));
timer->start();
}

File Main.cpp

int main(){
     while(1){
        updateProgressBar();
    }
return 1;
}

Thank you

QTimer is fired from the Qt internal event loop.

Your code will create an infinite number of QTimer and will eventually crash.

If you program using Qt, you will avoid having an infinite loop as while (1), this wouldn't work as it will block Qt event loop.

Given that you seem to have an UI, your code should be within a class, in which case it would make more sense to declare your QTimer in the class definition as a private member and not as a pointer, then initialise it on the constructor.

class MyClass: public QObject
{
    Q_OBJECT

public:
    void startUpdateProgressBar() { 
        myTimer.singleShot(false);
        myTimer.start(1000);
    }

    void stopUpdateProgressBar() { 
        myTimer.stop();
    }

  private:
        QTimer myTimer;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM