[Qt-interest] how do use the timer to calculate the time duration

Ferenc Stelcz ferenc at stelcz.hu
Mon Jun 22 22:25:36 CEST 2009


Ferenc Stelcz wrote:

> Ok, last try:
> 
> you could try *restart()* instead of elapsed(), dunno if it will give you what 
> you want, or you can try the ugly way ::
> 
> for example:
> 
> void MyVoipClass::acceptCall()
> {
> 	QTime callAcceptedAt = QTime::currentTime();
> 	
> 	/*
> 	users are chatting with each other
> 	do your job here
> 	*/
> 
> 	QTime callAbortedAt = QTime::currentTime();
> 	
> 	qDebug("Parties were chatting for ( %d ) milliseconds.",
> 		callAcceptedAt.msecsTo(callAbortedAt)
> 		);
> 	//or you can call secsTo to get the call duration in seconds
> }

Hm, I think those 2 beers have had some bad sied-effects on me... :)

Suppose Yuvaraj wants to display the call duration time while parties are 
talking to each other.

So he has set up for example an LCD widget for displaying the call time. (lets 
call this callTimeWidget)
Now if the user presses the accept call button (lets call it btnAcceptCall) 
the LCD widget gets updated, always displaying the seconds elapsed since the 
button was clicked. If the user pushes the Hang up button (btnHangUp) the call 
gets aborted.

For updating the LCD widget every second we need a QTimer object with a 
timeout value of 1000ms (1 sec). (QTimer* callTimeUpdateTimer)
For storing the call time we need a private QTime variable, call this callTime.

mmmm.. lets call the main class MyVoipClass.

void MyVoipClass::MyVoipClass
{
	callTimeWidget = new QLCDNumber(this);
	callTimeWidget->display( QString("00:00:00") );

	callTimeUpdateTimer = new QTimer(this);
	
	connect(btnAcceptCall,
		SIGNAL(clicked()),
		this,
		SLOT(acceptCall())
		);

	connect(btnHangUp,
		SIGNAL(clicked()),
		this,
		SLOT(hangUp())
		);

	connect(
		callTimeUpdateTimer,
		SIGNAL(timeout()),
		this,
		SLOT(updateCallDuration())
		);
}

Now imagine that we have created a slot in MyVoipClass, called 
updateCallDuration();

void MyVoipClass::updateCallDuration()
{
	callTime.addSecs(1);
	callTimeWidget->display( callTime.toString("HH:mm:ss") );
}

The acceptCall slot could look like this:

void MyVoipClass::acceptCall()
{
	callTime = QTime(0, 0, 0, 0);
	callDurationTimer->start();
}

Then the hangUp slot like this:

void MyVoipClass::hangUp()
{
	callDurationTimer->stop();
}

What do you think of this Yuvaraj?

--
Ferenc Stelcz
Junior Software Engineer

Banyan Technologies LLC.



More information about the Qt-interest-old mailing list