I have derived a custom widget my_widget from QWidget. There is a factory function in my MainWindow that creates those widgets, and their destroy-signal is connected to a slot in the MainWindow to do some cleanup.


Problem: qobject_cast returns zero when I try to cast the QOjbect* the slot received to my_widget*.

If I try the cast directly in the factory function, that works.
If I use plain-cast in the slot, it works too (the pointer is the same as returned by tthe factory function).
If I try to qobject_cast to a QWidget*, that works too.


Qt Code:
  1. my_widget* create_my_widget(QWidget* parent = nullptr)
  2. {
  3. auto w = new my_widget(parent);
  4.  
  5. QObject* ppp = (QObject*)w;
  6. auto sss = qobject_cast<my_widget*>(ppp); //works!
  7.  
  8. connect(w, &my_widget::destroyed, this, &MainWindow::remove_mywidget_widget);
  9. return w;
  10. }
To copy to clipboard, switch view to plain text mode 


slot:

Qt Code:
  1. void MainWindow::remove_mywidget_widget(QObject* removed)
  2. {
  3. auto mywid = qobject_cast<my_widget*>(removed); //Fails!
  4. auto mywid2 = my_widget::staticMetaObject.cast(removed); //Fails!
  5. auto mywid3 = qobject_cast<QWidget*>(removed); //Works!
  6. auto mywid4 = (my_widget*)removed; //Works!
  7.  
  8. ...
  9.  
  10. }
To copy to clipboard, switch view to plain text mode 


Where am I going wrong?