Displaying a live timer in a window
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:
Code:
void delay()
{
while( QTime::currentTime() < dieTime
) }
MainWindow
::MainWindow(QWidget *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
Code:
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
Re: Displaying a live timer in a window
Create a QTimer.
Connect the timeout() signal to a slot.
Set interval.
Start the timer.
Have fun.
Re: Displaying a live timer in a window
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.
Re: Displaying a live timer in a window
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...
Re: Displaying a live timer in a window
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.