PDA

View Full Version : Displaying a live timer in a window



aemara
15th January 2014, 13:54
Hi guys

I've been trying to use QTcreator to display a timer in a dialog or window. I start the timer, then use a delay function, then measure the time elapsed. My goal is to continuously display the time elapsed onto the window, as if I had a live timer, but it seems that every time I output the time elapsed to the window, it only outputs the final time ie if I use a delay of 5 seconds, then my window takes 5 seconds to open, then it displays 5 seconds; when in fact i want the window to open instantly and diplay 1,2,3,4,5.

Here's what I have so far:



void delay()
{
QTime dieTime= QTime::currentTime().addSecs(3);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEve nts, 100);
}


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QElapsedTimer timer;
timer.start();
delay();
connect(timer.elapsed(),SIGNAL(valueChange(int)), ui->progressBar,SLOT(setValue(int))); // but apparently timer.elapsed doesn't work as a const QObject



Then I tried another approach



for (int i=1; i<=3000; i++)
while (!timer.hasExpired(3000))
{
ui->lineEdit->setText(QString::number(timer.elapsed())); // trying to display timer in line edit
ui->progressBar->setValue(timer.elapsed()/30); // trying to use a progress bar to track the time
}


Does anyone have good pointers to help me solve this?

Thanks in advance

-Emara

boudie
15th January 2014, 15:55
Create a QTimer.
Connect the timeout() signal to a slot.
Set interval.
Start the timer.
Have fun.

aemara
15th January 2014, 18:30
I've tried that now, but now it doesn't even update the time. I changed the Second "this" to ui->progressBar, and the progress bar just shows me 24.
Do you mind expanding your answer a little bit more? I just started using QT last week so I might be doing something else wrong.

Thank you for your reply.

boudie
16th January 2014, 21:23
Start reading this:
http://qt-project.org/doc/qt-4.8/qtimer.html

I don't think a QElapsedTimer is the right class to use, but I might be misunderstanding your goal...

ChrisW67
17th January 2014, 04:36
Use QTime::start() to start recording elapsed time on a QTime object. Use QTimer (or some other mechanism) to periodically fire a slot and update a display with the current QTime::elapsed() time from the QTime object. No loops, no processEvents() calls.