Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Qtimer parent delete?



  • Hi
    I creat a Qtimer with a parent

    QNetworkReply* reply=manager->get(req);
    QTimer* timouteReply=new QTimer(reply);
    timouteReply->singleShot(TIMEOUT_REQUEST,this,SLOT(timouteReply()));
    

    after if reply call the finished i delete reply

    reply->deletelater();
    

    But somme time after the timeout() of timouteReply are call!

    I think when i call reply->deletelater(); when reply are deleted he need delete childrent then he need delete timouteReply!

    what is wrong?

    If you can help me thanks you.


  • Lifetime Qt Champion

    Hi,

    What is "some time" ?
    What is the timeout value of your timer ?
    Why not cancel it when your reply has finished ?


  • Qt Champions 2017

    1. use deletelater.
    2. Hope you have connected the network reply with slots. When the reply comes back from network reply, inside the slot just call timouteReply.stop(..)


  • thanks for your reply but after many test i fund if i creat a timer, run singelshot() and delete timer
    for exemple

    	QTimer * t=new QTimer();
    	t->singleShot(1000,this,SLOT(timeout()));
    	delete(t);
    

    the timout are call

    and i have found this thread
    https://lists.qt-project.org/pipermail/qt-interest-old/2009-October/013926.html

    I'is normal? or i need open a issue?

    (use deletelater do not solve problems)


  • Moderators

    I'is normal? or i need open a issue?

    Yes, it's normal. singleShot() is a static method so it doesn't matter if you call it statically ( with ::) or on an object (with ->). It always calls the same static function. You don't need that timer object at all.

    As for your problem - the slot timeout tries to access an object that lives shorter than the connection that is made with singleShot. To make sure the connection lives only as long as that object you need to pass a scope object for that connection. That scope object is the second parameter of singleShot. You gave it this which makes little sense in that scenario. Give it an object that lives only as long as the reply, so, for example, the reply object itself:

    QNetworkReply* reply=manager->get(req);
    QTimer::singleShot(TIMEOUT_REQUEST, reply, [=]{ timeout(); });
    

    This way the connection is severed when reply is deleted and the timer will cancel the timeout.



  • thanks you
    i confirme

    connect(timouteReply,SIGNAL(timeout()),this,SLOT(timoutReply()));
    timouteReply->setInterval(TIMEOUT_REQUEST);
    timouteReply->setSingleShot(1);
    timouteReply->start();
    

    work fine

    i have never see single shoot are not only a fast way to set a timer in setSingleShot.


Log in to reply