Search code examples
c++qtqtimerqtime

QTime to QTimer


How can I transform QTime to QTimer so I could print the left time to qDebug? Here's some code:

QTime time = QTime::fromString("23:54", "hh:mm");

How can I take one second away from time every second and print the left time to qDebug?


Solution

  • You just have to use a QTimer that triggers every second, then you must decrease the time with addSecs(-1) and print it in an appropriate format:

    #include <QCoreApplication>
    #include <QTimer>
    #include <QTime>
    #include <QDebug>
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QTimer timer;
    
        QTime time = QTime::fromString("23:54", "hh:mm");
    
        QObject::connect(&timer, &QTimer::timeout, [&time](){
            time = time.addSecs(-1);
            qDebug()<<time.toString("hh:mm:ss");
        });
        timer.start(1000);
    
        return a.exec();
    }