How to use QTimer inside for loop

  • Hi all. I've got a problem using QTimer (countdown timer) in for loop


    class myClass : public QMainWindow
        explicit business(QWidget *parent = 0);
    private slots:
        void countdownTimer();
        Ui::business *ui;
        QSqlDatabase db;
        int sec;
        bool isActive;
        QTimer *timer;
        list<dataClass> list_;


    void myClass::f(){
       list<dataClass>::iterator iter = list_.begin();
       for(; iter != list_.end(); ++iter)
            timer = new QTimer(this); //QTimer *timer; 
            isActive = true;    //bool isActive 
            connect(timer, SIGNAL(timeout()), 
            this, SLOT(countdownTimer()));
            //some code for waiting while isActive equal false 
            //and than next loop through
           //while(isActive != false);  
           //don't work(infinity loop) 
    void myClass::countdownTimer()
           if(seconds < 0) //int seconds = 10 e.g.
           isActive = false;

  • Lifetime Qt Champion

    What is the problem?

    your "void countdownTimer(") don't seem to belong to a class
    connect(timer, SIGNAL(timeout()), this, SLOT(countdownTimer()));
    tries to connect to this->countdownTimer()

  • Lifetime Qt Champion

    If u want to wait for 10 sec and then do something
    Why not just set the timer for 10 secs and when it fires, time has past?
    timer->start(10000); // call after 10 secs

  • @mrjj it's all ok))) I add some code from .h and .cpp

  • Lifetime Qt Champion

    Ok :)
    please set as "Solved" using the Topic Tools Button at first post :)

  • @mrjj No,no,no. it's ok from your first reply. Problem is in another.

  • Lifetime Qt Champion

    if you make loops, you stop the message queue and the timer signal may never be sent.
    at least put in a
    while(isActive != false) {
    in the loop to might have it work.

    It would be better to use slot and signal than looping as in
    Qt loops will give you pain.

  • @mrjj It doesn't work, unfortunately. It walks through "for" loop only one time.
    How can i solve this using slot & signal?

  • Lifetime Qt Champion

    @illyaSlobozhanin said:

    for(; iter != list_.end(); ++iter)

    But how many are in the list?
    It will go though the for loop as many times as there are
    dataClass in it.

    If you explain what you are trying to do.
    seems like
    for each database
    wait 10 secs

    but really not sure :)

  • @mrjj There're more than 1 object in list =)
    It's all ok. i forgot to change variable "isActive" in slot :D
    Thanks a lot!

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.