I'm having another weird problem... This time it has to do with type casting and metatypes in Qt. There is this function qobject_cast, which is defined as such:
template <class T> inline T qobject_cast(QObject *object) { return qobject_cast_helper<T>(object, T(0)); } //... template <class T> inline T qobject_cast_helper(QObject *object, T) { return static_cast<T>(((T)0)->staticMetaObject.cast(object)); } //and somewhere else QObject *QMetaObject::cast(QObject *obj) const { if (obj) { const QMetaObject *m = obj->metaObject(); do { if (m == this) return const_cast<QObject*>(obj); } while ((m = m->d.superdata)); } return 0; }
Now, in the gui library, this code is called to determine, if the layout is the child of another layout:
if (parent()) { QLayout *parentLayout = qobject_cast<QLayout*>(parent()); if (!parentLayout) { //complain that the parent is not a layout (and crash)
In this case the parent is a QHBoxLayout, which is a child of QLayout. Now, what happens is, that two different programs call this code. One is a small test of the mainwindow abilities in libQtGui, another one is the demo browser using libQtWebKit. But this is all so, basically it is the same condition in both cases. BUT the first case succeeds, and the second fails. That is, in the first case qobject_cast returns a pointer to the QLayout version of parent, in the second it returns a NULL pointer.
What happens is, that QMetaObject::cast() is called with "this" pointing at 0x0. Now, I can do this to make it work:
REPLACE
QLayout *parentLayout = qobject_cast
WITH
QLayout *parentLayout = (QLayout *)(((QLayout *)0)->staticMetaObject).cast(parent());
Now ::cast() is called with the real pointer.
My question is: Why does this replacement work when the original fails?? And why does this very same code work for one program UNDER THE EXACT SAME CONDITIONS but not another?
NOTE: This is all Qt code, basically I have modified nothing, except for the replacement code above.