In one of 开发者_高级运维my projects I am working with a QTimer and I wonderer whether it is possible to get the remaining time of a QTimer in order to let the user know "Time until next timeout: 10 secs" or something like that... Is that possible? If not so, has anyone good ideas for how to realize that?
Maybe I got to write my own Timer...
Is this what you are looking for ? QTimer::elapsed() uses the computers clock so depending on your platform the accuracy varies.
class MyTimer : QTimer
{
MyTimer(QObject* parent) : QTimer(parent)
{
connect(this, timeout(), this, resettime());
}
int start()
{
m_time.start();
return QTimer::start();
}
int start(int msec)
{
m_time.start();
return QTimer::start(msec)l
}
int timeLeft()
{
return interval()-m_time.elapsed()
}
private slots:
void resettime()
{
m_time.restart();
}
private:
QTime m_time;
}
Thanks for your advice, but I found another solution. I wrote my own class my_timer which simply has it's on internal secondary timer who times out every second. In my main window I connect this timeout with a function with updates the display for the user.
The my_timer.cpp:
#include "my_timer.hpp"
my_timer::my_timer( QWidget *parent ) : QTimer( parent )
{
notifier = new QTimer;
}
my_timer::~my_timer()
{
//...
}
QTimer* my_timer::get_notifier()
{
return notifier;
}
void my_timer::start( int msec )
{
QTimer::start( msec );
notifier->start( 1000 );
}
void my_timer::stop()
{
QTimer::stop();
notifier->stop();
}
And in my main_window.cpp:
void main_window::setup_connects()
{
// ...
connect( m_timer->get_notifier(), SIGNAL(timeout()), this, SLOT(on_update_label()) );
// ...
}
void main_window::on_update_label()
{
if( m_timer->isActive() )
{
if( remaining_secs > 1 )
{
remaining_secs--;
}
else
{
remaining_secs = spin_box->value();
}
update_label();
}
}
void main_window::update_label()
{
m_time_string = QString( "Remaining time until next execution: %1" ).arg( remaining_secs );
m_time_label->setText( m_time_string );
}
Have a look to the timerEvent
event from QObject. I think you can achieve what you want with this.
fir the sake of completeness:
#ifndef _ELAPSED_TIMER_H_
#define _ELAPSED_TIMER_H_
#include <QTimer>
#include <QTime>
/*
* convenience class, which can return the proportion of the time left. usefull for interpolation
* tasks
**/
class ElapsedTimer : public QTimer
{
Q_OBJECT
public:
ElapsedTimer(QObject* parent) : QTimer(parent)
{
connect(this, SIGNAL(timeout()), this, SLOT(resettime()));
}
void start()
{
m_time.start();
QTimer::start();
}
void start(int msec)
{
m_time.start();
QTimer::start(msec);
}
double proportionLeft()
{
return (interval()-m_time.elapsed())/interval();
}
int timeLeft()
{
return interval()-m_time.elapsed();
}
private slots:
void resettime()
{
m_time.restart();
}
private:
QTime m_time;
};
#endif/*_ELAPSED_TIMER_H_*/
精彩评论