David Levy David Levy - 9 days ago 5
C++ Question

Qt test current object/widget existence

In Qt I have to wait for 1 second and let event process so I use

QTime lDieTime= QTime::currentTime().addSecs(1);
while (QTime::currentTime() < lDieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);


But after this while, I do operation on the object (
this->mListIP.currentItem();
)

This work fine if the object has not been destroyed during the processEvents. But the object can be destroyed during this loop.

How can I test that the widget/object still exist?

I have tried
if(!this->isVisible())
but it crash (read access violation) because this does not exist anymore

My problem is related to this question

So if I can't check if this exist, how can I stop my function if the object is destroyed? Something in the destructor? A try-catch (but I dont like that)

Note : the function is called by a timerEvent from a QBasicTimer every 2 seconds

Edit : structure of the code :

Class A (Widget)
-constructor start a QBasicTimer of 2 seconds
-timerEvent, called by the QBasicTimer every two seconds
Layout containing Class A can destroy Class A object


Inside the timerevent, i start an operation, wait for 1 seconds, then try to update the widget. But I cant update it if it's been destroyed

edit2 : more code

void MaryAnnConnectionWidget::timerEvent( QTimerEvent * /*aEvent*/ )
{
//operation base on a socket and a udp broadcast
...

QTime lDieTime= QTime::currentTime().addSecs(1);
while (QTime::currentTime() < lDieTime)
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

//Operation to handle answers from the broadcast
...

if(this==nullptr) //Exit if we changed window <= CRASH HERE if widget destroyed
return;

//Handle the answers and displays results
...

}

Answer

If you need a safe pointer to a QObject, use QPointer. It will become null when the object is destroyed. It isn't clear how your code is constructed and where you're trying to do this, but you can also connect to the object's "destroyed" signal, and tie that to a slot that aborts the timer so that it doesn't attempt to reference the object.

Comments