Stopwatch with wrong time

Asked

Viewed 273 times

0

I have a timer made with Qtsdk, but when it starts time runs absurdly faster than normal. Follow the code below:

QTime time;
QTimer timer;

void PlanejamentoWidget::timeUpdate(){
    QTime t = ui.timeEdit->time();
    ui.timeEdit->setTime(t.addMSecs(time.elapsed()));
}

void PlanejamentoWidget::startTimer(){
    if (timer.isActive()){
       ui.btStart->setText("Iniciar");
       timer.stop();
    }
    else{       
        ui.btStart->setText("Parar");
        time.start();
        timer.start(60);
    }
}

void PlanejamentoWidget::restartTimer(){
    time.restart();
    QTime t;
    t.setHMS(0, 0, 0, 0);
    ui.timeEdit->setTime(t);
}

Does anyone have any idea what it might be? Thank you.

  • 2

    What is absurdly faster? How did you come to this conclusion? Give more details, it is difficult to understand the problem just with this information.

  • On the chronometer counter 10 seconds are equivalent to about 5 seconds of real time.

  • And this difference increases with the time of the chronometer.

  • 1

    The method timeUpdate is the call to each tick to your timer? Another thing, is just what you want to start the timer with the value 60? Just remembering that the expected value is in milliseconds...

  • Another thing: you probably want to change ui.timeEdit directly with the value of time.elapsed() and not add the time elapsed to what was already there in the Interface field. Probably this is the error.

  • Note that Qtcreator is just an IDE and does nothing but "organize" your project, the compiler on Windows is Visualstudio or Mingw. The term QT can be used to refer to qtSDK (which is a library with functions ready to facilitate development, especially in the case of cross-Platform).

  • 1

    If the difference is increasing it is because the timer is running more than once.

Show 2 more comments

1 answer

1

Your problem is that time.elapsed() is the amount time since you called time.start() in milliseconds. Therefore, the difference increases - the value is never zeroed.

To tidy up instead of calling #elapsed() use #restart():

    void PlanejamentoWidget::timeUpdate(){
        QTime t = ui.timeEdit->time();
        ui.timeEdit->setTime(t.addMSecs(time.restart()));
    }

The method #restart() returns the amount of time spent (in milliseconds) since the last call to #start() or #restart().

See more in: Qtime.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.