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












1















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.










share|improve this question



























    1















    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.










    share|improve this question

























      1












      1








      1








      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.










      share|improve this question














      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.







      c++ qt timer






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 14:29









      FloellaFloella

      584419




      584419
























          1 Answer
          1






          active

          oldest

          votes


















          2














          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






          share|improve this answer



















          • 1





            Maybe instead of global, make it a member variable?

            – TrebuchetMS
            Nov 24 '18 at 15:01











          • @TrebuchetMS Yes, was just thinking of using global for test purpose. Also, stopping/deleting the timer after it finished its objective so it doesn't waste CPU time would be nice.

            – Lucas Mota
            Nov 24 '18 at 15:12











          • I've tried this but I must be doing something wrong, as I do get my timer set to 1:00 but nothing else happens. In the header file I added a QTime *time = new QTime(0, 1, 0) as a public attribute (as well as the QTimer *timer I already had). In the cpp file I added these two lines in the updateCountdown() slot: time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));. It seems I'm missing something, as nothing seems to be happening. I also tried just declaring a QTime* timein header and then time = new QTime(0, 1, 0); in cpp. I didn't attempt the "when it gets to 0:00" yet.

            – Floella
            Nov 24 '18 at 23:11













          • You could check if the updateCountdown() is actually being called every second by printing the time->toString("m:ss"). If it's being called and the output is right, maybe the ui is not being updated correctly.

            – Lucas Mota
            Nov 25 '18 at 3:19






          • 1





            Well, finally got it to work but I wasn't able to use the QTime constructor. So instead I declared a public QTime time object in my header file and then, in the MainWindow constructor I used time.setHMS(0,1,0) to initialize it. Then, like @LucasMota said, I called time=time.addSecs(-1) and ui->countdown->setText(time.toString("m:ss")) within my updateCountdown() slot. I also change label initialization to ui->countdown->setText(time.toString("m:ss")) in the MainWindow constructor. Thanks.

            – Floella
            Nov 26 '18 at 13:20











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459173%2fqt-c-how-to-add-a-simple-countdown-timer%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          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






          share|improve this answer



















          • 1





            Maybe instead of global, make it a member variable?

            – TrebuchetMS
            Nov 24 '18 at 15:01











          • @TrebuchetMS Yes, was just thinking of using global for test purpose. Also, stopping/deleting the timer after it finished its objective so it doesn't waste CPU time would be nice.

            – Lucas Mota
            Nov 24 '18 at 15:12











          • I've tried this but I must be doing something wrong, as I do get my timer set to 1:00 but nothing else happens. In the header file I added a QTime *time = new QTime(0, 1, 0) as a public attribute (as well as the QTimer *timer I already had). In the cpp file I added these two lines in the updateCountdown() slot: time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));. It seems I'm missing something, as nothing seems to be happening. I also tried just declaring a QTime* timein header and then time = new QTime(0, 1, 0); in cpp. I didn't attempt the "when it gets to 0:00" yet.

            – Floella
            Nov 24 '18 at 23:11













          • You could check if the updateCountdown() is actually being called every second by printing the time->toString("m:ss"). If it's being called and the output is right, maybe the ui is not being updated correctly.

            – Lucas Mota
            Nov 25 '18 at 3:19






          • 1





            Well, finally got it to work but I wasn't able to use the QTime constructor. So instead I declared a public QTime time object in my header file and then, in the MainWindow constructor I used time.setHMS(0,1,0) to initialize it. Then, like @LucasMota said, I called time=time.addSecs(-1) and ui->countdown->setText(time.toString("m:ss")) within my updateCountdown() slot. I also change label initialization to ui->countdown->setText(time.toString("m:ss")) in the MainWindow constructor. Thanks.

            – Floella
            Nov 26 '18 at 13:20
















          2














          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






          share|improve this answer



















          • 1





            Maybe instead of global, make it a member variable?

            – TrebuchetMS
            Nov 24 '18 at 15:01











          • @TrebuchetMS Yes, was just thinking of using global for test purpose. Also, stopping/deleting the timer after it finished its objective so it doesn't waste CPU time would be nice.

            – Lucas Mota
            Nov 24 '18 at 15:12











          • I've tried this but I must be doing something wrong, as I do get my timer set to 1:00 but nothing else happens. In the header file I added a QTime *time = new QTime(0, 1, 0) as a public attribute (as well as the QTimer *timer I already had). In the cpp file I added these two lines in the updateCountdown() slot: time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));. It seems I'm missing something, as nothing seems to be happening. I also tried just declaring a QTime* timein header and then time = new QTime(0, 1, 0); in cpp. I didn't attempt the "when it gets to 0:00" yet.

            – Floella
            Nov 24 '18 at 23:11













          • You could check if the updateCountdown() is actually being called every second by printing the time->toString("m:ss"). If it's being called and the output is right, maybe the ui is not being updated correctly.

            – Lucas Mota
            Nov 25 '18 at 3:19






          • 1





            Well, finally got it to work but I wasn't able to use the QTime constructor. So instead I declared a public QTime time object in my header file and then, in the MainWindow constructor I used time.setHMS(0,1,0) to initialize it. Then, like @LucasMota said, I called time=time.addSecs(-1) and ui->countdown->setText(time.toString("m:ss")) within my updateCountdown() slot. I also change label initialization to ui->countdown->setText(time.toString("m:ss")) in the MainWindow constructor. Thanks.

            – Floella
            Nov 26 '18 at 13:20














          2












          2








          2







          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






          share|improve this answer













          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







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 24 '18 at 14:53









          Lucas MotaLucas Mota

          8817




          8817








          • 1





            Maybe instead of global, make it a member variable?

            – TrebuchetMS
            Nov 24 '18 at 15:01











          • @TrebuchetMS Yes, was just thinking of using global for test purpose. Also, stopping/deleting the timer after it finished its objective so it doesn't waste CPU time would be nice.

            – Lucas Mota
            Nov 24 '18 at 15:12











          • I've tried this but I must be doing something wrong, as I do get my timer set to 1:00 but nothing else happens. In the header file I added a QTime *time = new QTime(0, 1, 0) as a public attribute (as well as the QTimer *timer I already had). In the cpp file I added these two lines in the updateCountdown() slot: time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));. It seems I'm missing something, as nothing seems to be happening. I also tried just declaring a QTime* timein header and then time = new QTime(0, 1, 0); in cpp. I didn't attempt the "when it gets to 0:00" yet.

            – Floella
            Nov 24 '18 at 23:11













          • You could check if the updateCountdown() is actually being called every second by printing the time->toString("m:ss"). If it's being called and the output is right, maybe the ui is not being updated correctly.

            – Lucas Mota
            Nov 25 '18 at 3:19






          • 1





            Well, finally got it to work but I wasn't able to use the QTime constructor. So instead I declared a public QTime time object in my header file and then, in the MainWindow constructor I used time.setHMS(0,1,0) to initialize it. Then, like @LucasMota said, I called time=time.addSecs(-1) and ui->countdown->setText(time.toString("m:ss")) within my updateCountdown() slot. I also change label initialization to ui->countdown->setText(time.toString("m:ss")) in the MainWindow constructor. Thanks.

            – Floella
            Nov 26 '18 at 13:20














          • 1





            Maybe instead of global, make it a member variable?

            – TrebuchetMS
            Nov 24 '18 at 15:01











          • @TrebuchetMS Yes, was just thinking of using global for test purpose. Also, stopping/deleting the timer after it finished its objective so it doesn't waste CPU time would be nice.

            – Lucas Mota
            Nov 24 '18 at 15:12











          • I've tried this but I must be doing something wrong, as I do get my timer set to 1:00 but nothing else happens. In the header file I added a QTime *time = new QTime(0, 1, 0) as a public attribute (as well as the QTimer *timer I already had). In the cpp file I added these two lines in the updateCountdown() slot: time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));. It seems I'm missing something, as nothing seems to be happening. I also tried just declaring a QTime* timein header and then time = new QTime(0, 1, 0); in cpp. I didn't attempt the "when it gets to 0:00" yet.

            – Floella
            Nov 24 '18 at 23:11













          • You could check if the updateCountdown() is actually being called every second by printing the time->toString("m:ss"). If it's being called and the output is right, maybe the ui is not being updated correctly.

            – Lucas Mota
            Nov 25 '18 at 3:19






          • 1





            Well, finally got it to work but I wasn't able to use the QTime constructor. So instead I declared a public QTime time object in my header file and then, in the MainWindow constructor I used time.setHMS(0,1,0) to initialize it. Then, like @LucasMota said, I called time=time.addSecs(-1) and ui->countdown->setText(time.toString("m:ss")) within my updateCountdown() slot. I also change label initialization to ui->countdown->setText(time.toString("m:ss")) in the MainWindow constructor. Thanks.

            – Floella
            Nov 26 '18 at 13:20








          1




          1





          Maybe instead of global, make it a member variable?

          – TrebuchetMS
          Nov 24 '18 at 15:01





          Maybe instead of global, make it a member variable?

          – TrebuchetMS
          Nov 24 '18 at 15:01













          @TrebuchetMS Yes, was just thinking of using global for test purpose. Also, stopping/deleting the timer after it finished its objective so it doesn't waste CPU time would be nice.

          – Lucas Mota
          Nov 24 '18 at 15:12





          @TrebuchetMS Yes, was just thinking of using global for test purpose. Also, stopping/deleting the timer after it finished its objective so it doesn't waste CPU time would be nice.

          – Lucas Mota
          Nov 24 '18 at 15:12













          I've tried this but I must be doing something wrong, as I do get my timer set to 1:00 but nothing else happens. In the header file I added a QTime *time = new QTime(0, 1, 0) as a public attribute (as well as the QTimer *timer I already had). In the cpp file I added these two lines in the updateCountdown() slot: time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));. It seems I'm missing something, as nothing seems to be happening. I also tried just declaring a QTime* timein header and then time = new QTime(0, 1, 0); in cpp. I didn't attempt the "when it gets to 0:00" yet.

          – Floella
          Nov 24 '18 at 23:11







          I've tried this but I must be doing something wrong, as I do get my timer set to 1:00 but nothing else happens. In the header file I added a QTime *time = new QTime(0, 1, 0) as a public attribute (as well as the QTimer *timer I already had). In the cpp file I added these two lines in the updateCountdown() slot: time->addSecs(-1); ui->countdown->setText(time->toString("m:ss"));. It seems I'm missing something, as nothing seems to be happening. I also tried just declaring a QTime* timein header and then time = new QTime(0, 1, 0); in cpp. I didn't attempt the "when it gets to 0:00" yet.

          – Floella
          Nov 24 '18 at 23:11















          You could check if the updateCountdown() is actually being called every second by printing the time->toString("m:ss"). If it's being called and the output is right, maybe the ui is not being updated correctly.

          – Lucas Mota
          Nov 25 '18 at 3:19





          You could check if the updateCountdown() is actually being called every second by printing the time->toString("m:ss"). If it's being called and the output is right, maybe the ui is not being updated correctly.

          – Lucas Mota
          Nov 25 '18 at 3:19




          1




          1





          Well, finally got it to work but I wasn't able to use the QTime constructor. So instead I declared a public QTime time object in my header file and then, in the MainWindow constructor I used time.setHMS(0,1,0) to initialize it. Then, like @LucasMota said, I called time=time.addSecs(-1) and ui->countdown->setText(time.toString("m:ss")) within my updateCountdown() slot. I also change label initialization to ui->countdown->setText(time.toString("m:ss")) in the MainWindow constructor. Thanks.

          – Floella
          Nov 26 '18 at 13:20





          Well, finally got it to work but I wasn't able to use the QTime constructor. So instead I declared a public QTime time object in my header file and then, in the MainWindow constructor I used time.setHMS(0,1,0) to initialize it. Then, like @LucasMota said, I called time=time.addSecs(-1) and ui->countdown->setText(time.toString("m:ss")) within my updateCountdown() slot. I also change label initialization to ui->countdown->setText(time.toString("m:ss")) in the MainWindow constructor. Thanks.

          – Floella
          Nov 26 '18 at 13:20


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459173%2fqt-c-how-to-add-a-simple-countdown-timer%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

          Calculate evaluation metrics using cross_val_predict sklearn

          Insert data from modal to MySQL (multiple modal on website)