Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QTimer singleShot or delete
Qt 6.11 is out! See what's new in the release blog

QTimer singleShot or delete

Scheduled Pinned Locked Moved Solved General and Desktop
3 Posts 3 Posters 6.8k Views 3 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    tjudg
    wrote on last edited by
    #1

    Is there a difference between calling a singleShot timer and a regular timer with delete after? Is one way better than the other?
    For example:

    void MainWindow::on_pushButton_clicked()
    {
       timer = new QTimer();
       timer->start(5000);
       connect(timer,SIGNAL(timeout()),this,SLOT(timerDone()));
    }
    void MainWindow::timerDone()
    {
       delete timer;
       qDebug()<<"timer done";
    }
    
    void MainWindow::on_pushButton_clicked()
    {
       QTimer *timer = new QTimer();
       timer->start(5000);
       timer->setSingleShot(true);
       connect(timer,SIGNAL(timeout()),this,SLOT(timerDone()));
    }
    void MainWindow::timerDone()
    {
       qDebug()<<"timer done";
    }
    
    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      In the second case you wrote you have a memory leak. Setting single shot to true means that the timer will timeout only once after a call to start. not that it will be deleted after that.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      1
      • Chris KawaC Offline
        Chris KawaC Offline
        Chris Kawa
        Lifetime Qt Champion
        wrote on last edited by
        #3

        The first one has a bug. If main window is destroyed before the timer times out you have a memory leak.

        The second one also has a bug. You never delete the timer so you have a memory leak.

        If you just want a single shot just use the static method and don't bother with manual resource management:

        void MainWindow::on_pushButton_clicked()
        {
            QTimer::singleShot(5000, this, SLOT(timerDone()));
        }
        void MainWindow::timerDone()
        {
           qDebug()<<"timer done";
        }
        
        1 Reply Last reply
        1

        • Login

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved