Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Unsolved Do I need to delete QObjects?

    General and Desktop
    5
    5
    1812
    Loading More Posts
    • 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.
    • B
      Bob Asm last edited by Bob Asm

      Do I need to delete explicitly QObjects like in below code or Qt take care of that memory mangement by itself?

      void myClass:startTimer() {
        auto timer = new QTimer(this);
        timer->setInterval(1000*5);
         timer->setSingleShot(true);
        bool ok = connect(timer,  &QTtimer::timeout, [=]() {  loop->quit(); });
       assert(ok);
       timer->start();
       // do something 
       loop->quit();
      }
      
      1 Reply Last reply Reply Quote 0
      • mrjj
        mrjj Lifetime Qt Champion last edited by

        Hi
        When you assign a parent, you should not delete it manually. Parent will
        new QTimer(this); << this is owner.
        http://doc.qt.io/qt-5/objecttrees.html

        1 Reply Last reply Reply Quote 2
        • SGaist
          SGaist Lifetime Qt Champion last edited by

          Hi,

          The timer object will get automatically delete when its parent also is but the way you do it, you'll be filling up memory with QTimer objects each time you call your startTimer function. So either delete it explicitly at the end of the method or use a stack variable.

          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 Reply Quote 4
          • VRonin
            VRonin last edited by VRonin

            An alternative is to connect(timer, &QTimer::timeout,timer, &QTimer::deleteLater);

            P.S.
            You don't need to assert the return of connect when you use Qt5 connect syntax, the compiler will "static assert" it for you

            "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
            ~Napoleon Bonaparte

            On a crusade to banish setIndexWidget() from the holy land of Qt

            1 Reply Last reply Reply Quote 5
            • JKSH
              JKSH Moderators last edited by

              For this particular example, you don't need to create a QTimer object at all, so there is nothing to delete. Just use the static function, QTimer::singleShot().

              Your 6 lines of code can be reduced to 1 line:

                  QTimer::singleShot(  1000*5,  [=]{ loop->quit(); }  );
              

              Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

              1 Reply Last reply Reply Quote 5
              • First post
                Last post