tags:

views:

44

answers:

3

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...

+1  A: 

Have a look to the timerEvent event from QObject. I think you can achieve what you want with this.

Patrice Bernassola
+1  A: 

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 );
}
Exa
Not a bad approach, but if you are going to do this, I would encapsulate more of it into the my_timer class. For example, have an every_second signal and final_timeout signal, so that your classes that use it don't have to obtain the notifier timer and connect to it. You could also track the time passed and time remaining in that class.
Caleb Huitt - cjhuitt
A: 

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;
}
Harald Scheirich