adam.baker
adam.baker

Reputation: 1485

Why do qobject_cast and dynamic_cast fail in a slot connected to QWidget::destroyed?

I have a class Subclass, subclassed from QObject. I want to know when the item is deleted, so I connected this slot to the QWidget::destroyed() signal inherited by Subclass. But when I try to cast the argument to with qobject_cast, I get a zero result. The same result obtains from C++'s dynamic_cast. Why?

void MyClass::mySlot( QObject * item )
{
    qobject_cast<Subclass*>(item); // returns zero, even though item is a Subclass*
}

Upvotes: 2

Views: 2075

Answers (1)

adam.baker
adam.baker

Reputation: 1485

The reason is that by the time QObject::destroyed() is emitted, your derived class Subclass has already been destroyed. This is implied by the C++ order of destruction. Also, this question deals with a similar issue.

To get around this, you could either use C-style pointer casting (which is dispreferred), or rewrite your code to use a QObject instead.

Upvotes: 5

Related Questions