Search code examples
c++qttimer

Qt C++: how to add a simple countdown timer?


I'm new to Qt C++ and from the few resources I found online I wasn't able to extract only the bit I need to add a countdown timer to a form. I'm not trying to add any buttons or other functionality. Only need to have a timer starting at 1:00 and then decreasing until 0:00 is reached, at which point I need to show some sort of message indicating the user the time is up. I thought maybe adding a label to display the timer would be a simple way to do it (but now sure if I'm right on this).

So far I created a new Qt Application project, added a label to my main form and added some timer code to mainwindow.cpp from what I got at http://doc.qt.io/archives/qt-4.8/timers.html:

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //Initialize "countdown" label text
    ui->countdown->setText("1:00");

    //Connect timer to slot so it gets updated
    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(updateCountdown()));

    //It is started with a value of 1000 milliseconds, indicating that it will time out every second.
    timer->start(1000);
}

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

void MainWindow::updateCountdown()
{
    //do something along the lines of ui->countdown->setText(....);
}

In mainwindow.h I added a QTimer *timer; as a public attribute and also void updateCountdown(); as a private slot.

But I'm not exactly sure about how to go on from here. I think the next step is to decrease the timer each second and show that on the "countdown" label (which would be done on the updateCountdown slot) but I can't find out how. I'm also not sure how to trigger a message (maybe on a QFrame) when the countdown gets to 0:00.


Solution

  • From QTimer documentation, the function updateCountdown() is called every 1 second in your configuration. So you should decrease one second from your timer every time this function is called and update in the UI. Currently you are not storing your time anywhere, so I suggest you add it as a global for now, like QTime time(0, 1, 0) QTime Documentation.

    Then inside updateCountdown(), call time.addSecs(-1); and then ui->countdown->setText(time.toString("m:ss"));. Then is easy to check if it is "0:00" and do something else.

    I hope this helps