How to properly implement a count down timer in a QLabel

694 Views Asked by At

In order to shrink the problem I created a minimal verifiable example below. I am trying to implement a 60 minutes count down using a QLabel.

The problem I have is that instead of seeing the time going back, I see the the current time going forward. And no countdown goes back.

Below the minimal verifiable example:

mainwindow.h

#include <QMainWindow>
#include <QTime>
#include <QTimer>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

public slots:
    void timerUpdate();
private:
    Ui::MainWindow *ui;
    QTimer *timer;
    QTime time;
};

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //ui->countDown->setText(time.currentTime().toString("hh:mm:ss"));
    ui->countDown->setText("60:00");
    //ui->countDown->setText(time.toString("hh:mm:ss"));
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
    timer->start(1000);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::timerUpdate()
{
    time = time.addSecs(-1);
    ui->countDown->setText(time.currentTime().toString("hh:mm:ss"));
}

main.cpp

#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

EDIT 2

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //ui->countDown->setText(time.toString("hh:mm:ss"));
    //ui->countDown->setText("60:00");
    ui->countDown->setText(time.toString("hh:mm:ss"));
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
    timer->start(1000);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::timerUpdate()
{
    time = time.addSecs(-1);
    ui->countDown->setText(time.toString("hh:mm:ss"));
}

I followed exactly the official documentation but despite that it still does not work. In addition to that I consulted also the QTime class to make sure I was respecting the members function to call. I tried also another thign which is setting the constructor to setHMS and providing the proper values related to 1 hour, but that also didn't work.

I dug more and came across this post which uses a very similar approach to what I used, with the difference that the example implements a current timer and not a count down. That is the reason why in the timerUpdate() function I am diminishing time time = time.addSecs(-1); instead of adding it. But still does not work.

Thanks for pointing in the right direction to solve this problem.

0

There are 0 best solutions below