Poriferous
Poriferous

Reputation: 1582

Using QTimer for displaying timer

I created a class called aTimer which inherits from QTimer. I want to be able to store the time elapsed into a variable called TimeElapsed of type int. I then want to have the timer automatically started when the main window opens and for it to display the time elapsed therein.

I think I'm using the wrong timer, and I am quite confused as to which tools to be using within Qt because there are different ways of handling time. Suffice it to say that I want a stop-watch kind of module that allows me to start and stop time manually without a cap (or an interval with the case of Timer). How shall I proceed? So far, attempts to use QTimer are fruitless.

Upvotes: 0

Views: 2184

Answers (1)

Bowdzone
Bowdzone

Reputation: 3854

You do not really need a derived class for this task. I'd probably use a QTimer and a QElapsedTimer.

Create them in your main window constructor and set the QTimers interval according to how often the time should be updated. Also connect its timeout() signal to a function updating the displayed value. In this function you can get the elapsed time from the QElapsedTimer and update the display.

// *.h
QTimer* timer;
QElapsedTimer *eltimer;

// *.cpp
constructor(){
    this->timer = new QTimer(this);
    this->timer->setInterval(1000);
    connect(this->timer, SIGNAL(timeout()), this, SLOT(update_ui()));
    this->timer->start();

    this->eltimer = new QElapsedTimer(this);
    this->eltimer->start();
}

SLOT update_ui(){
    qint64 msecs_elapsed = this->eltimer->elapsed();
    // Insert value into ui object
}

Of course you can create some buttons to start() and stop() the QTimer

Upvotes: 1

Related Questions